metal_atlas.rs

  1use crate::{
  2    AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, DevicePixels, PlatformAtlas,
  3    Point, Size,
  4};
  5use anyhow::Result;
  6use collections::FxHashMap;
  7use derive_more::{Deref, DerefMut};
  8use etagere::BucketedAtlasAllocator;
  9use metal::Device;
 10use parking_lot::Mutex;
 11use std::borrow::Cow;
 12
 13pub(crate) struct MetalAtlas(Mutex<MetalAtlasState>);
 14
 15impl MetalAtlas {
 16    pub(crate) fn new(device: Device) -> Self {
 17        MetalAtlas(Mutex::new(MetalAtlasState {
 18            device: AssertSend(device),
 19            monochrome_textures: Default::default(),
 20            polychrome_textures: Default::default(),
 21            path_textures: Default::default(),
 22            tiles_by_key: Default::default(),
 23        }))
 24    }
 25
 26    pub(crate) fn metal_texture(&self, id: AtlasTextureId) -> metal::Texture {
 27        self.0.lock().texture(id).metal_texture.clone()
 28    }
 29
 30    pub(crate) fn allocate(
 31        &self,
 32        size: Size<DevicePixels>,
 33        texture_kind: AtlasTextureKind,
 34    ) -> AtlasTile {
 35        self.0.lock().allocate(size, texture_kind)
 36    }
 37
 38    pub(crate) fn clear_textures(&self, texture_kind: AtlasTextureKind) {
 39        let mut lock = self.0.lock();
 40        let textures = match texture_kind {
 41            AtlasTextureKind::Monochrome => &mut lock.monochrome_textures,
 42            AtlasTextureKind::Polychrome => &mut lock.polychrome_textures,
 43            AtlasTextureKind::Path => &mut lock.path_textures,
 44        };
 45        for texture in textures {
 46            texture.clear();
 47        }
 48    }
 49}
 50
 51struct MetalAtlasState {
 52    device: AssertSend<Device>,
 53    monochrome_textures: Vec<MetalAtlasTexture>,
 54    polychrome_textures: Vec<MetalAtlasTexture>,
 55    path_textures: Vec<MetalAtlasTexture>,
 56    tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
 57}
 58
 59impl PlatformAtlas for MetalAtlas {
 60    fn get_or_insert_with<'a>(
 61        &self,
 62        key: &AtlasKey,
 63        build: &mut dyn FnMut() -> Result<(Size<DevicePixels>, Cow<'a, [u8]>)>,
 64    ) -> Result<AtlasTile> {
 65        let mut lock = self.0.lock();
 66        if let Some(tile) = lock.tiles_by_key.get(key) {
 67            Ok(tile.clone())
 68        } else {
 69            let (size, bytes) = build()?;
 70            let tile = lock.allocate(size, key.texture_kind());
 71            let texture = lock.texture(tile.texture_id);
 72            texture.upload(tile.bounds, &bytes);
 73            lock.tiles_by_key.insert(key.clone(), tile.clone());
 74            Ok(tile)
 75        }
 76    }
 77}
 78
 79impl MetalAtlasState {
 80    fn allocate(&mut self, size: Size<DevicePixels>, texture_kind: AtlasTextureKind) -> AtlasTile {
 81        let textures = match texture_kind {
 82            AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
 83            AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
 84            AtlasTextureKind::Path => &mut self.path_textures,
 85        };
 86        textures
 87            .iter_mut()
 88            .rev()
 89            .find_map(|texture| texture.allocate(size))
 90            .unwrap_or_else(|| {
 91                let texture = self.push_texture(size, texture_kind);
 92                texture.allocate(size).unwrap()
 93            })
 94    }
 95
 96    fn push_texture(
 97        &mut self,
 98        min_size: Size<DevicePixels>,
 99        kind: AtlasTextureKind,
100    ) -> &mut MetalAtlasTexture {
101        const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
102            width: DevicePixels(1024),
103            height: DevicePixels(1024),
104        };
105
106        let size = min_size.max(&DEFAULT_ATLAS_SIZE);
107        let texture_descriptor = metal::TextureDescriptor::new();
108        texture_descriptor.set_width(size.width.into());
109        texture_descriptor.set_height(size.height.into());
110        let pixel_format;
111        let usage;
112        match kind {
113            AtlasTextureKind::Monochrome => {
114                pixel_format = metal::MTLPixelFormat::A8Unorm;
115                usage = metal::MTLTextureUsage::ShaderRead;
116            }
117            AtlasTextureKind::Polychrome => {
118                pixel_format = metal::MTLPixelFormat::BGRA8Unorm;
119                usage = metal::MTLTextureUsage::ShaderRead;
120            }
121            AtlasTextureKind::Path => {
122                pixel_format = metal::MTLPixelFormat::R16Float;
123                usage = metal::MTLTextureUsage::RenderTarget | metal::MTLTextureUsage::ShaderRead;
124            }
125        }
126        texture_descriptor.set_pixel_format(pixel_format);
127        texture_descriptor.set_usage(usage);
128        let metal_texture = self.device.new_texture(&texture_descriptor);
129
130        let textures = match kind {
131            AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
132            AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
133            AtlasTextureKind::Path => &mut self.path_textures,
134        };
135        let atlas_texture = MetalAtlasTexture {
136            id: AtlasTextureId {
137                index: textures.len() as u32,
138                kind,
139            },
140            allocator: etagere::BucketedAtlasAllocator::new(size.into()),
141            metal_texture: AssertSend(metal_texture),
142        };
143        textures.push(atlas_texture);
144        textures.last_mut().unwrap()
145    }
146
147    fn texture(&self, id: AtlasTextureId) -> &MetalAtlasTexture {
148        let textures = match id.kind {
149            crate::AtlasTextureKind::Monochrome => &self.monochrome_textures,
150            crate::AtlasTextureKind::Polychrome => &self.polychrome_textures,
151            crate::AtlasTextureKind::Path => &self.path_textures,
152        };
153        &textures[id.index as usize]
154    }
155}
156
157struct MetalAtlasTexture {
158    id: AtlasTextureId,
159    allocator: BucketedAtlasAllocator,
160    metal_texture: AssertSend<metal::Texture>,
161}
162
163impl MetalAtlasTexture {
164    fn clear(&mut self) {
165        self.allocator.clear();
166    }
167
168    fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
169        let allocation = self.allocator.allocate(size.into())?;
170        let tile = AtlasTile {
171            texture_id: self.id,
172            tile_id: allocation.id.into(),
173            bounds: Bounds {
174                origin: allocation.rectangle.min.into(),
175                size,
176            },
177        };
178        Some(tile)
179    }
180
181    fn upload(&self, bounds: Bounds<DevicePixels>, bytes: &[u8]) {
182        let region = metal::MTLRegion::new_2d(
183            bounds.origin.x.into(),
184            bounds.origin.y.into(),
185            bounds.size.width.into(),
186            bounds.size.height.into(),
187        );
188        self.metal_texture.replace_region(
189            region,
190            0,
191            bytes.as_ptr() as *const _,
192            bounds.size.width.to_bytes(self.bytes_per_pixel()) as u64,
193        );
194    }
195
196    fn bytes_per_pixel(&self) -> u8 {
197        use metal::MTLPixelFormat::*;
198        match self.metal_texture.pixel_format() {
199            A8Unorm | R8Unorm => 1,
200            RGBA8Unorm | BGRA8Unorm => 4,
201            _ => unimplemented!(),
202        }
203    }
204}
205
206impl From<Size<DevicePixels>> for etagere::Size {
207    fn from(size: Size<DevicePixels>) -> Self {
208        etagere::Size::new(size.width.into(), size.height.into())
209    }
210}
211
212impl From<etagere::Point> for Point<DevicePixels> {
213    fn from(value: etagere::Point) -> Self {
214        Point {
215            x: DevicePixels::from(value.x),
216            y: DevicePixels::from(value.y),
217        }
218    }
219}
220
221impl From<etagere::Size> for Size<DevicePixels> {
222    fn from(size: etagere::Size) -> Self {
223        Size {
224            width: DevicePixels::from(size.width),
225            height: DevicePixels::from(size.height),
226        }
227    }
228}
229
230impl From<etagere::Rectangle> for Bounds<DevicePixels> {
231    fn from(rectangle: etagere::Rectangle) -> Self {
232        Bounds {
233            origin: rectangle.min.into(),
234            size: rectangle.size().into(),
235        }
236    }
237}
238
239#[derive(Deref, DerefMut)]
240struct AssertSend<T>(T);
241
242unsafe impl<T> Send for AssertSend<T> {}