use anyhow::{Context as _, Result};
use derive_more::Deref;
use etagere::BucketedAtlasAllocator;
use gpui::{
AtlasBackend, AtlasKey, AtlasState, AtlasTextureId, AtlasTextureKind, AtlasTextureList,
AtlasTile, Bounds, DevicePixels, PlatformAtlas, Point, Size,
};
use objc2::{rc::Retained, runtime::ProtocolObject};
use objc2_metal::{
MTLDevice, MTLOrigin, MTLPixelFormat, MTLRegion, MTLSize, MTLStorageMode, MTLTexture,
MTLTextureDescriptor, MTLTextureUsage,
};
use parking_lot::Mutex;
use std::borrow::Cow;
pub struct MetalAtlas(Mutex<AtlasState<MetalAtlasTextures>>);
impl MetalAtlas {
pub(crate) fn new(
device: Retained<ProtocolObject<dyn MTLDevice>>,
supports_shared_storage: bool,
) -> Self {
MetalAtlas(Mutex::new(AtlasState::new(MetalAtlasTextures {
device,
supports_shared_storage,
monochrome_textures: Default::default(),
polychrome_textures: Default::default(),
})))
}
pub(crate) fn metal_texture(
&self,
id: AtlasTextureId,
) -> Option<Retained<ProtocolObject<dyn MTLTexture>>> {
Some(self.0.lock().backend.texture(id)?.metal_texture.clone())
}
}
struct MetalAtlasTextures {
device: Retained<ProtocolObject<dyn MTLDevice>>,
supports_shared_storage: bool,
monochrome_textures: AtlasTextureList<MetalAtlasTexture>,
polychrome_textures: AtlasTextureList<MetalAtlasTexture>,
}
impl PlatformAtlas for MetalAtlas {
fn get_or_insert_with<'a>(
&self,
key: AtlasKey,
build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
) -> Result<Option<AtlasTile>> {
self.0.lock().get_or_insert_with(key, build)
}
fn remove(&self, key: &AtlasKey) {
self.0.lock().remove(key);
}
}
impl AtlasBackend for MetalAtlasTextures {
fn insert(
&mut self,
kind: AtlasTextureKind,
size: Size<DevicePixels>,
bytes: &[u8],
) -> Result<AtlasTile> {
let tile = self.allocate(size, kind).context("failed to allocate")?;
let texture = self
.texture(tile.texture_id)
.context("allocated tile refers to a missing texture")?;
texture.upload(tile.bounds, bytes);
Ok(tile)
}
fn remove(&mut self, tile: AtlasTile) {
let id = tile.texture_id;
let textures = match id.kind {
AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
AtlasTextureKind::Subpixel => unreachable!(),
};
let Some(texture_slot) = textures
.textures
.iter_mut()
.find(|texture| texture.as_ref().is_some_and(|v| v.id == id))
else {
return;
};
if let Some(mut texture) = texture_slot.take() {
texture.allocator.deallocate(tile.tile_id.into());
texture.decrement_ref_count();
if texture.is_unreferenced() {
textures.free_list.push(id.index as usize);
} else {
*texture_slot = Some(texture);
}
}
}
}
impl MetalAtlasTextures {
fn allocate(
&mut self,
size: Size<DevicePixels>,
texture_kind: AtlasTextureKind,
) -> Option<AtlasTile> {
{
let textures = match texture_kind {
AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
AtlasTextureKind::Subpixel => unreachable!(),
};
if let Some(tile) = textures
.iter_mut()
.rev()
.find_map(|texture| texture.allocate(size))
{
return Some(tile);
}
}
let texture = self.push_texture(size, texture_kind);
texture.allocate(size)
}
fn push_texture(
&mut self,
min_size: Size<DevicePixels>,
kind: AtlasTextureKind,
) -> &mut MetalAtlasTexture {
const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
width: DevicePixels(1024),
height: DevicePixels(1024),
};
const MAX_ATLAS_SIZE: Size<DevicePixels> = Size {
width: DevicePixels(16384),
height: DevicePixels(16384),
};
let size = min_size.min(&MAX_ATLAS_SIZE).max(&DEFAULT_ATLAS_SIZE);
let texture_descriptor = MTLTextureDescriptor::new();
unsafe {
texture_descriptor.setWidth(size.width.0 as usize);
texture_descriptor.setHeight(size.height.0 as usize);
}
let pixel_format;
let usage;
match kind {
AtlasTextureKind::Monochrome => {
pixel_format = MTLPixelFormat::A8Unorm;
usage = MTLTextureUsage::ShaderRead;
}
AtlasTextureKind::Polychrome => {
pixel_format = MTLPixelFormat::BGRA8Unorm;
usage = MTLTextureUsage::ShaderRead;
}
AtlasTextureKind::Subpixel => unreachable!(),
}
texture_descriptor.setPixelFormat(pixel_format);
texture_descriptor.setUsage(usage);
texture_descriptor.setStorageMode(if self.supports_shared_storage {
MTLStorageMode::Shared
} else {
MTLStorageMode::Managed
});
let metal_texture = self
.device
.newTextureWithDescriptor(&texture_descriptor)
.expect("failed to allocate Metal atlas texture");
let texture_list = match kind {
AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
AtlasTextureKind::Subpixel => unreachable!(),
};
let index = texture_list.free_list.pop();
let atlas_texture = MetalAtlasTexture {
id: AtlasTextureId {
index: index.unwrap_or(texture_list.textures.len()) as u32,
kind,
},
allocator: etagere::BucketedAtlasAllocator::new(size_to_etagere(size)),
metal_texture: AtlasTextureHandle(metal_texture),
live_atlas_keys: 0,
};
if let Some(ix) = index {
texture_list.textures[ix] = Some(atlas_texture);
texture_list.textures.get_mut(ix)
} else {
texture_list.textures.push(Some(atlas_texture));
texture_list.textures.last_mut()
}
.unwrap()
.as_mut()
.unwrap()
}
fn texture(&self, id: AtlasTextureId) -> Option<&MetalAtlasTexture> {
let textures = match id.kind {
AtlasTextureKind::Monochrome => &self.monochrome_textures,
AtlasTextureKind::Polychrome => &self.polychrome_textures,
AtlasTextureKind::Subpixel => unreachable!(),
};
textures.textures.get(id.index as usize)?.as_ref()
}
}
struct MetalAtlasTexture {
id: AtlasTextureId,
allocator: BucketedAtlasAllocator,
metal_texture: AtlasTextureHandle,
live_atlas_keys: u32,
}
impl MetalAtlasTexture {
fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
let allocation = self.allocator.allocate(size_to_etagere(size))?;
let tile = AtlasTile {
texture_id: self.id,
tile_id: allocation.id.into(),
bounds: Bounds {
origin: point_from_etagere(allocation.rectangle.min),
size,
},
padding: 0,
};
self.live_atlas_keys += 1;
Some(tile)
}
fn upload(&self, bounds: Bounds<DevicePixels>, bytes: &[u8]) {
let region = MTLRegion {
origin: MTLOrigin {
x: bounds.origin.x.0 as usize,
y: bounds.origin.y.0 as usize,
z: 0,
},
size: MTLSize {
width: bounds.size.width.0 as usize,
height: bounds.size.height.0 as usize,
depth: 1,
},
};
let row_bytes = bounds.size.width.to_bytes(self.bytes_per_pixel());
assert!(
bytes.len() >= row_bytes as usize * bounds.size.height.0 as usize,
"atlas upload must contain every pixel in the region"
);
unsafe {
self.metal_texture
.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
region,
0,
std::ptr::NonNull::new(bytes.as_ptr().cast_mut().cast()).unwrap(),
row_bytes as usize,
);
}
}
fn bytes_per_pixel(&self) -> u8 {
match self.metal_texture.pixelFormat() {
MTLPixelFormat::A8Unorm | MTLPixelFormat::R8Unorm => 1,
MTLPixelFormat::RGBA8Unorm | MTLPixelFormat::BGRA8Unorm => 4,
_ => unimplemented!(),
}
}
fn decrement_ref_count(&mut self) {
self.live_atlas_keys -= 1;
}
fn is_unreferenced(&mut self) -> bool {
self.live_atlas_keys == 0
}
}
fn size_to_etagere(size: Size<DevicePixels>) -> etagere::Size {
etagere::Size::new(size.width.into(), size.height.into())
}
fn point_from_etagere(value: etagere::Point) -> Point<DevicePixels> {
Point {
x: DevicePixels::from(value.x),
y: DevicePixels::from(value.y),
}
}
#[derive(Deref)]
struct AtlasTextureHandle(Retained<ProtocolObject<dyn MTLTexture>>);
unsafe impl Send for AtlasTextureHandle {}
#[cfg(test)]
mod tests {
use super::*;
use gpui::PlatformAtlas;
use std::borrow::Cow;
#[test]
fn objc2_atlas_upload_and_retained_texture_survive_eviction() {
objc2::rc::autoreleasepool(|_| {
let device =
objc2_metal::MTLCreateSystemDefaultDevice().expect("Metal device required");
let shared = device.supportsFamily(objc2_metal::MTLGPUFamily::Apple1);
let atlas = MetalAtlas::new(device, shared);
let size = Size {
width: DevicePixels(2),
height: DevicePixels(2),
};
let pixels = vec![13, 27, 61, 255].repeat(4);
let key = make_image_key(42, 0);
let tile = atlas
.get_or_insert_with(key.clone(), &mut || {
Ok(Some((size, Cow::Borrowed(pixels.as_slice()))))
})
.unwrap()
.unwrap();
let texture = atlas.metal_texture(tile.texture_id).unwrap();
atlas.remove(&key);
assert!(atlas.metal_texture(tile.texture_id).is_none());
drop(atlas);
let mut actual = vec![0u8; pixels.len()];
let region = MTLRegion {
origin: MTLOrigin {
x: tile.bounds.origin.x.0 as usize,
y: tile.bounds.origin.y.0 as usize,
z: 0,
},
size: MTLSize {
width: 2,
height: 2,
depth: 1,
},
};
unsafe {
texture.getBytes_bytesPerRow_fromRegion_mipmapLevel(
std::ptr::NonNull::new(actual.as_mut_ptr().cast()).unwrap(),
8,
region,
0,
);
}
assert_eq!(actual, pixels);
});
}
fn create_atlas() -> Option<MetalAtlas> {
let device = objc2_metal::MTLCreateSystemDefaultDevice()?;
Some(MetalAtlas::new(device, true))
}
fn make_image_key(image_id: usize, frame_index: usize) -> AtlasKey {
AtlasKey::Image(gpui::RenderImageParams {
image_id: gpui::ImageId(image_id),
frame_index,
})
}
fn insert_tile(atlas: &MetalAtlas, key: AtlasKey, size: Size<DevicePixels>) -> AtlasTile {
atlas
.get_or_insert_with(key, &mut || {
let byte_count = (size.width.0 as usize) * (size.height.0 as usize) * 4;
Ok(Some((size, Cow::Owned(vec![0u8; byte_count]))))
})
.expect("allocation should succeed")
.expect("callback returns Some")
}
#[test]
fn test_remove_clears_stale_keys_from_tiles_by_key() {
let Some(atlas) = create_atlas() else {
return;
};
let small = Size {
width: DevicePixels(64),
height: DevicePixels(64),
};
let key_a = make_image_key(1, 0);
let key_b = make_image_key(2, 0);
let key_c = make_image_key(3, 0);
let tile_a = insert_tile(&atlas, key_a.clone(), small);
let tile_b = insert_tile(&atlas, key_b.clone(), small);
let tile_c = insert_tile(&atlas, key_c.clone(), small);
assert_eq!(tile_a.texture_id, tile_b.texture_id);
assert_eq!(tile_b.texture_id, tile_c.texture_id);
atlas.remove(&key_a);
atlas.remove(&key_b);
atlas.remove(&key_c);
let tile_a2 = insert_tile(&atlas, key_a, small);
assert!(atlas.metal_texture(tile_a2.texture_id).is_some());
}
#[test]
fn test_metal_texture_is_none_after_last_tile_removed() {
let Some(atlas) = create_atlas() else {
return;
};
let key = make_image_key(1, 0);
let tile = insert_tile(
&atlas,
key.clone(),
Size {
width: DevicePixels(64),
height: DevicePixels(64),
},
);
assert!(atlas.metal_texture(tile.texture_id).is_some());
atlas.remove(&key);
assert!(atlas.metal_texture(tile.texture_id).is_none());
}
#[test]
fn test_remove_deallocates_tile_space_for_reuse() {
let Some(atlas) = create_atlas() else {
return;
};
let small = Size {
width: DevicePixels(64),
height: DevicePixels(64),
};
let big = Size {
width: DevicePixels(700),
height: DevicePixels(700),
};
let keeper_key = make_image_key(1, 0);
let big_key_a = make_image_key(2, 0);
let big_key_b = make_image_key(3, 0);
let keeper_tile = insert_tile(&atlas, keeper_key, small);
let tile_a = insert_tile(&atlas, big_key_a.clone(), big);
assert_eq!(keeper_tile.texture_id, tile_a.texture_id);
atlas.remove(&big_key_a);
let tile_b = insert_tile(&atlas, big_key_b, big);
assert_eq!(tile_b.texture_id, keeper_tile.texture_id);
}
#[test]
fn test_remove_nonexistent_key_is_noop() {
let Some(atlas) = create_atlas() else {
return;
};
let key = make_image_key(999, 0);
atlas.remove(&key);
}
}