Skip to main content

gpui_wgpu/
wgpu_atlas.rs

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    /// Distinguishes new textures that reuse an [`AtlasTextureId`].
45    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    /// Returns the view backing `id`, or `None` once every tile in it has been
80    /// removed. A scene can still reference such a texture when a cached view
81    /// replays a paint from before the image was dropped, so callers must skip
82    /// those sprites rather than assume the texture exists.
83    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    /// Clears all cached textures and tiles, forcing them to be recreated.
93    /// Use this for incremental recovery when the device is still valid.
94    pub fn clear(&self) {
95        self.0.lock().clear(|textures| {
96            textures.storage = WgpuAtlasStorage::default();
97            textures.pending_uploads.clear();
98        });
99    }
100
101    /// Handles device lost by clearing all textures and cached tiles.
102    /// The atlas will lazily recreate textures as needed on subsequent frames.
103    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                })
417                .await
418                .map_err(|error| anyhow::anyhow!("failed to request adapter: {error}"))?;
419            let (device, queue) = adapter
420                .request_device(&wgpu::DeviceDescriptor {
421                    label: Some("wgpu_atlas_test_device"),
422                    required_features: wgpu::Features::empty(),
423                    required_limits: wgpu::Limits::downlevel_defaults()
424                        .using_resolution(adapter.limits())
425                        .using_alignment(adapter.limits()),
426                    memory_hints: wgpu::MemoryHints::MemoryUsage,
427                    trace: wgpu::Trace::Off,
428                    experimental_features: wgpu::ExperimentalFeatures::disabled(),
429                })
430                .await
431                .map_err(|error| anyhow::anyhow!("failed to request device: {error}"))?;
432            Ok((Arc::new(device), Arc::new(queue)))
433        })
434    }
435
436    #[test]
437    fn before_frame_skips_uploads_for_removed_texture() -> anyhow::Result<()> {
438        let (device, queue) = test_device_and_queue()?;
439
440        let atlas = WgpuAtlas::new(device, queue, wgpu::TextureFormat::Bgra8Unorm);
441        let key = AtlasKey::Image(RenderImageParams {
442            image_id: ImageId(1),
443            frame_index: 0,
444        });
445        let size = Size {
446            width: DevicePixels(1),
447            height: DevicePixels(1),
448        };
449        let mut build = || Ok(Some((size, Cow::Owned(vec![0, 0, 0, 255]))));
450
451        // Regression test: before the fix, this panicked in flush_uploads
452        atlas
453            .get_or_insert_with(key.clone(), &mut build)?
454            .expect("tile should be created");
455        atlas.remove(&key);
456        atlas.before_frame();
457        Ok(())
458    }
459
460    #[test]
461    fn remove_deallocates_tile_space_for_reuse() -> anyhow::Result<()> {
462        let (device, queue) = test_device_and_queue()?;
463        let atlas = WgpuAtlas::new(device, queue, wgpu::TextureFormat::Bgra8Unorm);
464
465        let small = Size {
466            width: DevicePixels(64),
467            height: DevicePixels(64),
468        };
469        let big = Size {
470            width: DevicePixels(700),
471            height: DevicePixels(700),
472        };
473
474        let make_key = |image_id: usize| {
475            AtlasKey::Image(RenderImageParams {
476                image_id: ImageId(image_id),
477                frame_index: 0,
478            })
479        };
480        let insert = |key: AtlasKey, size: Size<DevicePixels>| {
481            let byte_count = (size.width.0 as usize) * (size.height.0 as usize) * 4;
482            atlas
483                .get_or_insert_with(key, &mut || {
484                    Ok(Some((size, Cow::Owned(vec![0u8; byte_count]))))
485                })
486                .expect("allocation should succeed")
487                .expect("callback returns Some")
488        };
489
490        let keeper_key = make_key(1);
491        let big_key_a = make_key(2);
492        let big_key_b = make_key(3);
493
494        let keeper_tile = insert(keeper_key, small);
495        let tile_a = insert(big_key_a.clone(), big);
496        assert_eq!(keeper_tile.texture_id, tile_a.texture_id);
497
498        atlas.remove(&big_key_a);
499        let tile_b = insert(big_key_b, big);
500        assert_eq!(tile_b.texture_id, keeper_tile.texture_id);
501        Ok(())
502    }
503
504    #[test]
505    fn reused_texture_id_has_new_generation() -> anyhow::Result<()> {
506        let (device, queue) = test_device_and_queue()?;
507        let atlas = WgpuAtlas::new(device, queue, wgpu::TextureFormat::Bgra8Unorm);
508        let size = Size {
509            width: DevicePixels(700),
510            height: DevicePixels(700),
511        };
512        let make_key = |image_id| {
513            AtlasKey::Image(RenderImageParams {
514                image_id: ImageId(image_id),
515                frame_index: 0,
516            })
517        };
518        let insert = |key: AtlasKey| {
519            atlas
520                .get_or_insert_with(key, &mut || {
521                    Ok(Some((
522                        size,
523                        Cow::Owned(vec![0; size.width.0 as usize * size.height.0 as usize * 4]),
524                    )))
525                })
526                .expect("allocation should succeed")
527                .expect("callback returns Some")
528        };
529
530        let first_key = make_key(1);
531        let first_tile = insert(first_key.clone());
532        let first_generation = atlas
533            .get_texture_info(first_tile.texture_id)
534            .context("first texture should exist")?
535            .generation;
536        atlas.remove(&first_key);
537        assert!(atlas.get_texture_info(first_tile.texture_id).is_none());
538
539        let second_tile = insert(make_key(2));
540        let second_generation = atlas
541            .get_texture_info(second_tile.texture_id)
542            .context("second texture should exist")?
543            .generation;
544
545        assert_eq!(second_tile.texture_id, first_tile.texture_id);
546        assert_ne!(second_generation, first_generation);
547        Ok(())
548    }
549
550    #[test]
551    fn swizzle_upload_data_preserves_bgra_uploads() {
552        let input = vec![0x10, 0x20, 0x30, 0x40];
553        assert_eq!(
554            swizzle_upload_data(&input, wgpu::TextureFormat::Bgra8Unorm),
555            input
556        );
557    }
558
559    #[test]
560    fn swizzle_upload_data_converts_bgra_to_rgba() {
561        let input = vec![0x10, 0x20, 0x30, 0x40, 0xAA, 0xBB, 0xCC, 0xDD];
562        assert_eq!(
563            swizzle_upload_data(&input, wgpu::TextureFormat::Rgba8Unorm),
564            vec![0x30, 0x20, 0x10, 0x40, 0xCC, 0xBB, 0xAA, 0xDD]
565        );
566    }
567}