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
 87        textures
 88            .iter_mut()
 89            .rev()
 90            .find_map(|texture| texture.allocate(size))
 91            .unwrap_or_else(|| {
 92                let texture = self.push_texture(size, texture_kind);
 93                texture.allocate(size).unwrap()
 94            })
 95    }
 96
 97    fn push_texture(
 98        &mut self,
 99        min_size: Size<DevicePixels>,
100        kind: AtlasTextureKind,
101    ) -> &mut MetalAtlasTexture {
102        const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
103            width: DevicePixels(1024),
104            height: DevicePixels(1024),
105        };
106        // Max texture size on all modern Apple GPUs. Anything bigger than that crashes in validateWithDevice.
107        const MAX_ATLAS_SIZE: Size<DevicePixels> = Size {
108            width: DevicePixels(16384),
109            height: DevicePixels(16384),
110        };
111        let size = min_size.min(&MAX_ATLAS_SIZE).max(&DEFAULT_ATLAS_SIZE);
112        let texture_descriptor = metal::TextureDescriptor::new();
113        texture_descriptor.set_width(size.width.into());
114        texture_descriptor.set_height(size.height.into());
115        let pixel_format;
116        let usage;
117        match kind {
118            AtlasTextureKind::Monochrome => {
119                pixel_format = metal::MTLPixelFormat::A8Unorm;
120                usage = metal::MTLTextureUsage::ShaderRead;
121            }
122            AtlasTextureKind::Polychrome => {
123                pixel_format = metal::MTLPixelFormat::BGRA8Unorm;
124                usage = metal::MTLTextureUsage::ShaderRead;
125            }
126            AtlasTextureKind::Path => {
127                pixel_format = metal::MTLPixelFormat::R16Float;
128                usage = metal::MTLTextureUsage::RenderTarget | metal::MTLTextureUsage::ShaderRead;
129            }
130        }
131        texture_descriptor.set_pixel_format(pixel_format);
132        texture_descriptor.set_usage(usage);
133        let metal_texture = self.device.new_texture(&texture_descriptor);
134
135        let textures = match kind {
136            AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
137            AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
138            AtlasTextureKind::Path => &mut self.path_textures,
139        };
140        let atlas_texture = MetalAtlasTexture {
141            id: AtlasTextureId {
142                index: textures.len() as u32,
143                kind,
144            },
145            allocator: etagere::BucketedAtlasAllocator::new(size.into()),
146            metal_texture: AssertSend(metal_texture),
147        };
148        textures.push(atlas_texture);
149        textures.last_mut().unwrap()
150    }
151
152    fn texture(&self, id: AtlasTextureId) -> &MetalAtlasTexture {
153        let textures = match id.kind {
154            crate::AtlasTextureKind::Monochrome => &self.monochrome_textures,
155            crate::AtlasTextureKind::Polychrome => &self.polychrome_textures,
156            crate::AtlasTextureKind::Path => &self.path_textures,
157        };
158        &textures[id.index as usize]
159    }
160}
161
162struct MetalAtlasTexture {
163    id: AtlasTextureId,
164    allocator: BucketedAtlasAllocator,
165    metal_texture: AssertSend<metal::Texture>,
166}
167
168impl MetalAtlasTexture {
169    fn clear(&mut self) {
170        self.allocator.clear();
171    }
172
173    fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
174        let allocation = self.allocator.allocate(size.into())?;
175        let tile = AtlasTile {
176            texture_id: self.id,
177            tile_id: allocation.id.into(),
178            bounds: Bounds {
179                origin: allocation.rectangle.min.into(),
180                size,
181            },
182            padding: 0,
183        };
184        Some(tile)
185    }
186
187    fn upload(&self, bounds: Bounds<DevicePixels>, bytes: &[u8]) {
188        let region = metal::MTLRegion::new_2d(
189            bounds.origin.x.into(),
190            bounds.origin.y.into(),
191            bounds.size.width.into(),
192            bounds.size.height.into(),
193        );
194        self.metal_texture.replace_region(
195            region,
196            0,
197            bytes.as_ptr() as *const _,
198            bounds.size.width.to_bytes(self.bytes_per_pixel()) as u64,
199        );
200    }
201
202    fn bytes_per_pixel(&self) -> u8 {
203        use metal::MTLPixelFormat::*;
204        match self.metal_texture.pixel_format() {
205            A8Unorm | R8Unorm => 1,
206            RGBA8Unorm | BGRA8Unorm => 4,
207            _ => unimplemented!(),
208        }
209    }
210}
211
212impl From<Size<DevicePixels>> for etagere::Size {
213    fn from(size: Size<DevicePixels>) -> Self {
214        etagere::Size::new(size.width.into(), size.height.into())
215    }
216}
217
218impl From<etagere::Point> for Point<DevicePixels> {
219    fn from(value: etagere::Point) -> Self {
220        Point {
221            x: DevicePixels::from(value.x),
222            y: DevicePixels::from(value.y),
223        }
224    }
225}
226
227impl From<etagere::Size> for Size<DevicePixels> {
228    fn from(size: etagere::Size) -> Self {
229        Size {
230            width: DevicePixels::from(size.width),
231            height: DevicePixels::from(size.height),
232        }
233    }
234}
235
236impl From<etagere::Rectangle> for Bounds<DevicePixels> {
237    fn from(rectangle: etagere::Rectangle) -> Self {
238        Bounds {
239            origin: rectangle.min.into(),
240            size: rectangle.size().into(),
241        }
242    }
243}
244
245#[derive(Deref, DerefMut)]
246struct AssertSend<T>(T);
247
248unsafe impl<T> Send for AssertSend<T> {}