1use anyhow::{Context as _, Result};
2use etagere::{BucketedAtlasAllocator, size2};
3use gpui_engine::{
4 AtlasBackend, AtlasKey, AtlasState, AtlasTextureId, AtlasTextureKind, AtlasTextureList,
5 AtlasTile, PlatformAtlas,
6};
7use gpui_platform::{Bounds, DevicePixels, Point, Size};
8use parking_lot::Mutex;
9use std::{borrow::Cow, ops, sync::Arc};
10
11use crate::WgpuContext;
12
13fn device_size_to_etagere(size: Size<DevicePixels>) -> etagere::Size {
14 size2(size.width.0, size.height.0)
15}
16
17fn etagere_point_to_device(point: etagere::Point) -> Point<DevicePixels> {
18 Point {
19 x: DevicePixels(point.x),
20 y: DevicePixels(point.y),
21 }
22}
23
24pub struct WgpuAtlas(Mutex<AtlasState<WgpuAtlasTextures>>);
25
26struct PendingUpload {
27 id: AtlasTextureId,
28 bounds: Bounds<DevicePixels>,
29 data: Vec<u8>,
30}
31
32struct WgpuAtlasTextures {
33 device: Arc<wgpu::Device>,
34 queue: Arc<wgpu::Queue>,
35 max_texture_size: u32,
36 color_texture_format: wgpu::TextureFormat,
37 storage: WgpuAtlasStorage,
38 pending_uploads: Vec<PendingUpload>,
39 next_texture_generation: u64,
40}
41
42pub struct WgpuTextureInfo {
43 pub view: wgpu::TextureView,
44 pub generation: u64,
46}
47
48impl WgpuAtlas {
49 pub fn new(
50 device: Arc<wgpu::Device>,
51 queue: Arc<wgpu::Queue>,
52 color_texture_format: wgpu::TextureFormat,
53 ) -> Self {
54 let max_texture_size = device.limits().max_texture_dimension_2d;
55 WgpuAtlas(Mutex::new(AtlasState::new(WgpuAtlasTextures {
56 device,
57 queue,
58 max_texture_size,
59 color_texture_format,
60 storage: WgpuAtlasStorage::default(),
61 pending_uploads: Vec::new(),
62 next_texture_generation: 0,
63 })))
64 }
65
66 pub fn from_context(context: &WgpuContext) -> Self {
67 Self::new(
68 context.device.clone(),
69 context.queue.clone(),
70 context.color_texture_format(),
71 )
72 }
73
74 pub fn before_frame(&self) {
75 let mut lock = self.0.lock();
76 lock.backend.flush_uploads();
77 }
78
79 pub fn get_texture_info(&self, id: AtlasTextureId) -> Option<WgpuTextureInfo> {
84 let lock = self.0.lock();
85 let texture = lock.backend.storage.get(id)?;
86 Some(WgpuTextureInfo {
87 view: texture.view.clone(),
88 generation: texture.generation,
89 })
90 }
91
92 pub fn clear(&self) {
95 self.0.lock().clear(|textures| {
96 textures.storage = WgpuAtlasStorage::default();
97 textures.pending_uploads.clear();
98 });
99 }
100
101 pub fn handle_device_lost(&self, context: &WgpuContext) {
104 self.0.lock().clear(|textures| {
105 textures.device = context.device.clone();
106 textures.queue = context.queue.clone();
107 textures.color_texture_format = context.color_texture_format();
108 textures.storage = WgpuAtlasStorage::default();
109 textures.pending_uploads.clear();
110 });
111 }
112}
113
114impl PlatformAtlas for WgpuAtlas {
115 fn get_or_insert_with<'a>(
116 &self,
117 key: AtlasKey,
118 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
119 ) -> Result<Option<AtlasTile>> {
120 self.0.lock().get_or_insert_with(key, build)
121 }
122
123 fn remove(&self, key: &AtlasKey) {
124 self.0.lock().remove(key);
125 }
126}
127
128impl AtlasBackend for WgpuAtlasTextures {
129 fn insert(
130 &mut self,
131 kind: AtlasTextureKind,
132 size: Size<DevicePixels>,
133 bytes: &[u8],
134 ) -> Result<AtlasTile> {
135 let tile = self.allocate(size, kind).context("failed to allocate")?;
136 self.upload_texture(tile.texture_id, tile.bounds, bytes);
137 Ok(tile)
138 }
139
140 fn remove(&mut self, tile: AtlasTile) {
141 let id = tile.texture_id;
142 let Some(texture_slot) = self.storage[id.kind].textures.get_mut(id.index as usize) else {
143 return;
144 };
145
146 if let Some(mut texture) = texture_slot.take() {
147 texture.allocator.deallocate(tile.tile_id.into());
148 texture.decrement_ref_count();
149 if texture.is_unreferenced() {
150 self.pending_uploads
151 .retain(|upload| upload.id != texture.id);
152 self.storage[id.kind]
153 .free_list
154 .push(texture.id.index as usize);
155 } else {
156 *texture_slot = Some(texture);
157 }
158 }
159 }
160}
161
162impl WgpuAtlasTextures {
163 fn allocate(
164 &mut self,
165 size: Size<DevicePixels>,
166 texture_kind: AtlasTextureKind,
167 ) -> Option<AtlasTile> {
168 {
169 let textures = &mut self.storage[texture_kind];
170
171 if let Some(tile) = textures
172 .iter_mut()
173 .rev()
174 .find_map(|texture| texture.allocate(size))
175 {
176 return Some(tile);
177 }
178 }
179
180 let texture = self.push_texture(size, texture_kind);
181 texture.allocate(size)
182 }
183
184 fn push_texture(
185 &mut self,
186 min_size: Size<DevicePixels>,
187 kind: AtlasTextureKind,
188 ) -> &mut WgpuAtlasTexture {
189 const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
190 width: DevicePixels(1024),
191 height: DevicePixels(1024),
192 };
193 let max_texture_size = self.max_texture_size as i32;
194 let max_atlas_size = Size {
195 width: DevicePixels(max_texture_size),
196 height: DevicePixels(max_texture_size),
197 };
198
199 let size = min_size.min(&max_atlas_size).max(&DEFAULT_ATLAS_SIZE);
200 let format = match kind {
201 AtlasTextureKind::Monochrome => wgpu::TextureFormat::R8Unorm,
202 AtlasTextureKind::Subpixel | AtlasTextureKind::Polychrome => self.color_texture_format,
203 };
204
205 let texture = self.device.create_texture(&wgpu::TextureDescriptor {
206 label: Some("atlas"),
207 size: wgpu::Extent3d {
208 width: size.width.0 as u32,
209 height: size.height.0 as u32,
210 depth_or_array_layers: 1,
211 },
212 mip_level_count: 1,
213 sample_count: 1,
214 dimension: wgpu::TextureDimension::D2,
215 format,
216 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
217 view_formats: &[],
218 });
219
220 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
221
222 let texture_list = &mut self.storage[kind];
223 let index = texture_list.free_list.pop();
224 let generation = self.next_texture_generation;
225 self.next_texture_generation = self.next_texture_generation.wrapping_add(1);
226
227 let atlas_texture = WgpuAtlasTexture {
228 id: AtlasTextureId {
229 index: index.unwrap_or(texture_list.textures.len()) as u32,
230 kind,
231 },
232 generation,
233 allocator: BucketedAtlasAllocator::new(device_size_to_etagere(size)),
234 format,
235 texture,
236 view,
237 live_atlas_keys: 0,
238 };
239
240 if let Some(ix) = index {
241 texture_list.textures[ix] = Some(atlas_texture);
242 texture_list
243 .textures
244 .get_mut(ix)
245 .and_then(|t| t.as_mut())
246 .expect("texture must exist")
247 } else {
248 texture_list.textures.push(Some(atlas_texture));
249 texture_list
250 .textures
251 .last_mut()
252 .and_then(|t| t.as_mut())
253 .expect("texture must exist")
254 }
255 }
256
257 fn upload_texture(&mut self, id: AtlasTextureId, bounds: Bounds<DevicePixels>, bytes: &[u8]) {
258 let data = self
259 .storage
260 .get(id)
261 .map(|texture| swizzle_upload_data(bytes, texture.format))
262 .unwrap_or_else(|| bytes.to_vec());
263
264 self.pending_uploads
265 .push(PendingUpload { id, bounds, data });
266 }
267
268 fn flush_uploads(&mut self) {
269 for upload in self.pending_uploads.drain(..) {
270 let Some(texture) = self.storage.get(upload.id) else {
271 continue;
272 };
273 let bytes_per_pixel = texture.bytes_per_pixel();
274
275 self.queue.write_texture(
276 wgpu::TexelCopyTextureInfo {
277 texture: &texture.texture,
278 mip_level: 0,
279 origin: wgpu::Origin3d {
280 x: upload.bounds.origin.x.0 as u32,
281 y: upload.bounds.origin.y.0 as u32,
282 z: 0,
283 },
284 aspect: wgpu::TextureAspect::All,
285 },
286 &upload.data,
287 wgpu::TexelCopyBufferLayout {
288 offset: 0,
289 bytes_per_row: Some(upload.bounds.size.width.0 as u32 * bytes_per_pixel as u32),
290 rows_per_image: None,
291 },
292 wgpu::Extent3d {
293 width: upload.bounds.size.width.0 as u32,
294 height: upload.bounds.size.height.0 as u32,
295 depth_or_array_layers: 1,
296 },
297 );
298 }
299 }
300}
301
302#[derive(Default)]
303struct WgpuAtlasStorage {
304 monochrome_textures: AtlasTextureList<WgpuAtlasTexture>,
305 subpixel_textures: AtlasTextureList<WgpuAtlasTexture>,
306 polychrome_textures: AtlasTextureList<WgpuAtlasTexture>,
307}
308
309impl ops::Index<AtlasTextureKind> for WgpuAtlasStorage {
310 type Output = AtlasTextureList<WgpuAtlasTexture>;
311 fn index(&self, kind: AtlasTextureKind) -> &Self::Output {
312 match kind {
313 AtlasTextureKind::Monochrome => &self.monochrome_textures,
314 AtlasTextureKind::Subpixel => &self.subpixel_textures,
315 AtlasTextureKind::Polychrome => &self.polychrome_textures,
316 }
317 }
318}
319
320impl ops::IndexMut<AtlasTextureKind> for WgpuAtlasStorage {
321 fn index_mut(&mut self, kind: AtlasTextureKind) -> &mut Self::Output {
322 match kind {
323 AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
324 AtlasTextureKind::Subpixel => &mut self.subpixel_textures,
325 AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
326 }
327 }
328}
329
330impl WgpuAtlasStorage {
331 fn get(&self, id: AtlasTextureId) -> Option<&WgpuAtlasTexture> {
332 self[id.kind]
333 .textures
334 .get(id.index as usize)
335 .and_then(|t| t.as_ref())
336 }
337}
338
339struct WgpuAtlasTexture {
340 id: AtlasTextureId,
341 generation: u64,
342 allocator: BucketedAtlasAllocator,
343 texture: wgpu::Texture,
344 view: wgpu::TextureView,
345 format: wgpu::TextureFormat,
346 live_atlas_keys: u32,
347}
348
349impl WgpuAtlasTexture {
350 fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
351 let allocation = self.allocator.allocate(device_size_to_etagere(size))?;
352 let tile = AtlasTile {
353 texture_id: self.id,
354 tile_id: allocation.id.into(),
355 padding: 0,
356 bounds: Bounds {
357 origin: etagere_point_to_device(allocation.rectangle.min),
358 size,
359 },
360 };
361 self.live_atlas_keys += 1;
362 Some(tile)
363 }
364
365 fn bytes_per_pixel(&self) -> u8 {
366 match self.format {
367 wgpu::TextureFormat::R8Unorm => 1,
368 wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm => 4,
369 _ => 4,
370 }
371 }
372
373 fn decrement_ref_count(&mut self) {
374 self.live_atlas_keys -= 1;
375 }
376
377 fn is_unreferenced(&self) -> bool {
378 self.live_atlas_keys == 0
379 }
380}
381
382fn swizzle_upload_data(bytes: &[u8], format: wgpu::TextureFormat) -> Vec<u8> {
383 match format {
384 wgpu::TextureFormat::Rgba8Unorm => {
385 let mut data = bytes.to_vec();
386 for pixel in data.chunks_exact_mut(4) {
387 pixel.swap(0, 2);
388 }
389 data
390 }
391 _ => bytes.to_vec(),
392 }
393}
394
395#[cfg(all(test, not(target_family = "wasm")))]
396mod tests {
397 use super::*;
398 use gpui_engine::{ImageId, RenderImageParams};
399 use pollster::block_on;
400 use std::sync::Arc;
401
402 fn test_device_and_queue() -> anyhow::Result<(Arc<wgpu::Device>, Arc<wgpu::Queue>)> {
403 block_on(async {
404 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
405 backends: wgpu::Backends::all(),
406 flags: wgpu::InstanceFlags::default(),
407 backend_options: wgpu::BackendOptions::default(),
408 memory_budget_thresholds: wgpu::MemoryBudgetThresholds::default(),
409 display: None,
410 });
411 let adapter = instance
412 .request_adapter(&wgpu::RequestAdapterOptions {
413 power_preference: wgpu::PowerPreference::LowPower,
414 compatible_surface: None,
415 force_fallback_adapter: false,
416 apply_limit_buckets: false,
417 })
418 .await
419 .map_err(|error| anyhow::anyhow!("failed to request adapter: {error}"))?;
420 let (device, queue) = adapter
421 .request_device(&wgpu::DeviceDescriptor {
422 label: Some("wgpu_atlas_test_device"),
423 required_features: wgpu::Features::empty(),
424 required_limits: wgpu::Limits::downlevel_defaults()
425 .using_resolution(adapter.limits())
426 .using_alignment(adapter.limits()),
427 memory_hints: wgpu::MemoryHints::MemoryUsage,
428 trace: wgpu::Trace::Off,
429 experimental_features: wgpu::ExperimentalFeatures::disabled(),
430 })
431 .await
432 .map_err(|error| anyhow::anyhow!("failed to request device: {error}"))?;
433 Ok((Arc::new(device), Arc::new(queue)))
434 })
435 }
436
437 #[test]
438 fn before_frame_skips_uploads_for_removed_texture() -> anyhow::Result<()> {
439 let (device, queue) = test_device_and_queue()?;
440
441 let atlas = WgpuAtlas::new(device, queue, wgpu::TextureFormat::Bgra8Unorm);
442 let key = AtlasKey::Image(RenderImageParams {
443 image_id: ImageId(1),
444 frame_index: 0,
445 });
446 let size = Size {
447 width: DevicePixels(1),
448 height: DevicePixels(1),
449 };
450 let mut build = || Ok(Some((size, Cow::Owned(vec![0, 0, 0, 255]))));
451
452 atlas
454 .get_or_insert_with(key.clone(), &mut build)?
455 .expect("tile should be created");
456 atlas.remove(&key);
457 atlas.before_frame();
458 Ok(())
459 }
460
461 #[test]
462 fn remove_deallocates_tile_space_for_reuse() -> anyhow::Result<()> {
463 let (device, queue) = test_device_and_queue()?;
464 let atlas = WgpuAtlas::new(device, queue, wgpu::TextureFormat::Bgra8Unorm);
465
466 let small = Size {
467 width: DevicePixels(64),
468 height: DevicePixels(64),
469 };
470 let big = Size {
471 width: DevicePixels(700),
472 height: DevicePixels(700),
473 };
474
475 let make_key = |image_id: usize| {
476 AtlasKey::Image(RenderImageParams {
477 image_id: ImageId(image_id),
478 frame_index: 0,
479 })
480 };
481 let insert = |key: AtlasKey, size: Size<DevicePixels>| {
482 let byte_count = (size.width.0 as usize) * (size.height.0 as usize) * 4;
483 atlas
484 .get_or_insert_with(key, &mut || {
485 Ok(Some((size, Cow::Owned(vec![0u8; byte_count]))))
486 })
487 .expect("allocation should succeed")
488 .expect("callback returns Some")
489 };
490
491 let keeper_key = make_key(1);
492 let big_key_a = make_key(2);
493 let big_key_b = make_key(3);
494
495 let keeper_tile = insert(keeper_key, small);
496 let tile_a = insert(big_key_a.clone(), big);
497 assert_eq!(keeper_tile.texture_id, tile_a.texture_id);
498
499 atlas.remove(&big_key_a);
500 let tile_b = insert(big_key_b, big);
501 assert_eq!(tile_b.texture_id, keeper_tile.texture_id);
502 Ok(())
503 }
504
505 #[test]
506 fn reused_texture_id_has_new_generation() -> anyhow::Result<()> {
507 let (device, queue) = test_device_and_queue()?;
508 let atlas = WgpuAtlas::new(device, queue, wgpu::TextureFormat::Bgra8Unorm);
509 let size = Size {
510 width: DevicePixels(700),
511 height: DevicePixels(700),
512 };
513 let make_key = |image_id| {
514 AtlasKey::Image(RenderImageParams {
515 image_id: ImageId(image_id),
516 frame_index: 0,
517 })
518 };
519 let insert = |key: AtlasKey| {
520 atlas
521 .get_or_insert_with(key, &mut || {
522 Ok(Some((
523 size,
524 Cow::Owned(vec![0; size.width.0 as usize * size.height.0 as usize * 4]),
525 )))
526 })
527 .expect("allocation should succeed")
528 .expect("callback returns Some")
529 };
530
531 let first_key = make_key(1);
532 let first_tile = insert(first_key.clone());
533 let first_generation = atlas
534 .get_texture_info(first_tile.texture_id)
535 .context("first texture should exist")?
536 .generation;
537 atlas.remove(&first_key);
538 assert!(atlas.get_texture_info(first_tile.texture_id).is_none());
539
540 let second_tile = insert(make_key(2));
541 let second_generation = atlas
542 .get_texture_info(second_tile.texture_id)
543 .context("second texture should exist")?
544 .generation;
545
546 assert_eq!(second_tile.texture_id, first_tile.texture_id);
547 assert_ne!(second_generation, first_generation);
548 Ok(())
549 }
550
551 #[test]
552 fn swizzle_upload_data_preserves_bgra_uploads() {
553 let input = vec![0x10, 0x20, 0x30, 0x40];
554 assert_eq!(
555 swizzle_upload_data(&input, wgpu::TextureFormat::Bgra8Unorm),
556 input
557 );
558 }
559
560 #[test]
561 fn swizzle_upload_data_converts_bgra_to_rgba() {
562 let input = vec![0x10, 0x20, 0x30, 0x40, 0xAA, 0xBB, 0xCC, 0xDD];
563 assert_eq!(
564 swizzle_upload_data(&input, wgpu::TextureFormat::Rgba8Unorm),
565 vec![0x30, 0x20, 0x10, 0x40, 0xCC, 0xBB, 0xAA, 0xDD]
566 );
567 }
568}