Skip to main content

gpui_wgpu/
wgpu_renderer.rs

1// Modified for gpui-pre (snapshot of zed@125ca86): adapt device queues and sRGB detection to wgpu 30.0.1.
2use crate::{CompositorGpuHint, DeviceErrorState, WgpuAtlas, WgpuContext};
3use anyhow::{Context as _, Result};
4use bytemuck::{Pod, Zeroable};
5use collections::FxHashMap;
6use gpui::{
7    AtlasTextureId, Bounds, DevicePixels, GpuSpecs, PaintedPath, PrimitiveBatch, ScaledPixels,
8    Scene, Size, get_gamma_correction_ratios, quad_depth, quad_depth_scale,
9};
10use log::warn;
11#[cfg(not(target_family = "wasm"))]
12use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
13use smallvec::SmallVec;
14use std::cell::RefCell;
15use std::num::NonZeroU64;
16use std::ops::Range;
17use std::rc::Rc;
18use std::sync::Arc;
19
20const MAX_INSTANCE_BUFFER_SIZE: u64 = 256 * 1024 * 1024;
21
22const INSTANCE_TEXTURE_TEXEL_SIZE: u64 = 16;
23
24/// Shader variant for backends with storage buffer support: the shared shader
25/// logic plus the storage-buffer instance transport.
26const STORAGE_BUFFER_SHADERS: &str = concat!(
27    include_str!("shaders.wgsl"),
28    include_str!("shaders_storage.wgsl"),
29);
30
31/// Shader variant for WebGL2, which has no storage buffers: the shared shader
32/// logic plus the texture-based instance transport.
33const WEBGL_SHADERS: &str = concat!(
34    include_str!("shaders.wgsl"),
35    include_str!("shaders_webgl.wgsl"),
36);
37
38/// Subpixel text rendering requires dual-source blending, which WebGL2 lacks, so
39/// this variant only ever runs with the storage-buffer transport. The `enable`
40/// directive must precede all declarations.
41const SUBPIXEL_SHADERS: &str = concat!(
42    "enable dual_source_blending;\n",
43    include_str!("shaders.wgsl"),
44    include_str!("shaders_storage.wgsl"),
45    include_str!("shaders_subpixel.wgsl"),
46);
47
48fn least_common_multiple(left: u64, right: u64) -> u64 {
49    let mut first = left;
50    let mut second = right;
51    while second != 0 {
52        let remainder = first % second;
53        first = second;
54        second = remainder;
55    }
56    left / first * right
57}
58
59#[repr(C)]
60#[derive(Clone, Copy, Pod, Zeroable)]
61struct GlobalParams {
62    viewport_size: [f32; 2],
63    path_paint_base: u32,
64    path_curve_base: u32,
65    depth_scale: f32,
66    quad_count: u32,
67    premultiplied_alpha: u32,
68    pad: u32,
69}
70
71const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
72
73struct DepthTexture {
74    texture: wgpu::Texture,
75    view: wgpu::TextureView,
76}
77
78#[repr(C)]
79#[derive(Clone, Copy, Pod, Zeroable)]
80struct PodBounds {
81    origin: [f32; 2],
82    size: [f32; 2],
83}
84
85impl From<Bounds<ScaledPixels>> for PodBounds {
86    fn from(bounds: Bounds<ScaledPixels>) -> Self {
87        Self {
88            origin: [bounds.origin.x.0, bounds.origin.y.0],
89            size: [bounds.size.width.0, bounds.size.height.0],
90        }
91    }
92}
93
94#[repr(C)]
95#[derive(Clone, Copy, Pod, Zeroable)]
96struct SurfaceParams {
97    bounds: PodBounds,
98    content_mask: PodBounds,
99}
100
101#[repr(C)]
102#[derive(Clone, Copy, Pod, Zeroable)]
103struct GammaParams {
104    gamma_ratios: [f32; 4],
105    grayscale_enhanced_contrast: f32,
106    subpixel_enhanced_contrast: f32,
107    is_bgr: u32,
108    _pad: u32,
109}
110
111pub struct WgpuSurfaceConfig {
112    pub size: Size<DevicePixels>,
113    pub transparent: bool,
114    /// Preferred presentation mode. When `Some`, the renderer will use this
115    /// mode if supported by the surface, falling back to `Fifo`.
116    /// When `None`, defaults to `Fifo` (VSync).
117    ///
118    /// Mobile platforms may prefer `Mailbox` (triple-buffering) to avoid
119    /// blocking in `get_current_texture()` during lifecycle transitions.
120    pub preferred_present_mode: Option<wgpu::PresentMode>,
121}
122
123struct WgpuPipelines {
124    quads: wgpu::RenderPipeline,
125    opaque_quads: wgpu::RenderPipeline,
126    shadows: wgpu::RenderPipeline,
127    path_tiles: wgpu::RenderPipeline,
128    underlines: wgpu::RenderPipeline,
129    mono_sprites: wgpu::RenderPipeline,
130    subpixel_sprites: Option<wgpu::RenderPipeline>,
131    poly_sprites: wgpu::RenderPipeline,
132    #[allow(dead_code)]
133    surfaces: wgpu::RenderPipeline,
134    premultiplied_alpha: bool,
135}
136
137/// One frame allocation of instance data, ready to bind.
138struct InstanceBinding {
139    bind_group: wgpu::BindGroup,
140    /// Index of the allocation's first instance within the bound data. Always
141    /// zero on the storage-buffer path, where the binding offset already
142    /// positions the array; on the WebGL texture path the shader indexes the
143    /// shared instance texture absolutely, so draws must offset their
144    /// instance (or vertex) ranges by this value.
145    first_instance: u32,
146}
147
148struct PathTileBinding {
149    tiles: InstanceBinding,
150    paint_base: u32,
151    curve_base: u32,
152}
153
154/// Where one array of instance data was written this frame.
155struct InstanceAllocation {
156    offset: u64,
157    size: u64,
158    first_instance: u32,
159}
160
161struct InstanceBindings {
162    quads: InstanceBinding,
163    shadows: InstanceBinding,
164    path_tiles: PathTileBinding,
165    underlines: InstanceBinding,
166    monochrome_sprites: InstanceBinding,
167    subpixel_sprites: InstanceBinding,
168    polychrome_sprites: InstanceBinding,
169}
170
171struct WgpuBindGroupLayouts {
172    globals: wgpu::BindGroupLayout,
173    instances: wgpu::BindGroupLayout,
174    path_tiles: wgpu::BindGroupLayout,
175    texture: wgpu::BindGroupLayout,
176    surfaces: wgpu::BindGroupLayout,
177}
178
179/// Shared GPU context reference, used to coordinate device recovery across multiple windows.
180pub type GpuContext = Rc<RefCell<Option<WgpuContext>>>;
181
182enum InstanceData {
183    Storage(wgpu::Buffer),
184    // WebGL2 has no storage buffers. A uint texture keeps the records available to both shader
185    // stages while preserving integer and floating-point bit patterns exactly.
186    Texture {
187        texture: wgpu::Texture,
188        view: wgpu::TextureView,
189        width: u32,
190        height: u32,
191    },
192}
193
194/// GPU resources that must be dropped together during device recovery.
195struct WgpuResources {
196    device: Arc<wgpu::Device>,
197    queue: Arc<wgpu::Queue>,
198    pipelines: WgpuPipelines,
199    bind_group_layouts: WgpuBindGroupLayouts,
200    atlas_sampler: wgpu::Sampler,
201    atlas_texture_bind_groups: FxHashMap<AtlasTextureId, CachedTextureBindGroup>,
202    globals_buffer: wgpu::Buffer,
203    globals_bind_group: wgpu::BindGroup,
204    instance_data: InstanceData,
205}
206
207struct CachedTextureBindGroup {
208    texture_generation: u64,
209    bind_group: wgpu::BindGroup,
210}
211
212struct WgpuRendererCore {
213    resources: WgpuResources,
214    atlas: Arc<WgpuAtlas>,
215    gamma_offset: u64,
216    instance_data_capacity: u64,
217    max_instance_data_size: u64,
218    instance_data_alignment: u64,
219    uses_webgl_instance_data: bool,
220    rendering_params: RenderingParameters,
221    is_bgr: bool,
222    dual_source_blending: bool,
223    transient_attachments: bool,
224    adapter_info: wgpu::AdapterInfo,
225    depth_texture: Option<DepthTexture>,
226    /// Read by the headless renderer to create its render target.
227    #[cfg(all(
228        not(target_family = "wasm"),
229        any(test, feature = "bench-support", feature = "test-support")
230    ))]
231    target_format: wgpu::TextureFormat,
232    max_texture_size: u32,
233}
234
235/// GPU resources of a windowed renderer. A surface is only ever configured against the
236/// device that owns `core`, so it cannot outlive it: there is no surface-only state.
237enum RendererState {
238    /// Frames can be drawn.
239    Ready {
240        surface: wgpu::Surface<'static>,
241        core: WgpuRendererCore,
242    },
243    /// The native surface is gone (Android `TerminateWindow`, browser context loss) but
244    /// the device, pipelines, and atlas remain so `replace_surface` can resume without
245    /// re-uploading cached textures.
246    Unconfigured { core: WgpuRendererCore },
247    /// Released by `destroy`, or dropped for a device recovery that has not succeeded yet.
248    Released,
249}
250
251pub struct WgpuRenderer {
252    /// Shared GPU context for device recovery coordination (unused on WASM).
253    #[allow(dead_code)]
254    context: Option<GpuContext>,
255    /// Compositor GPU hint for adapter selection (unused on WASM).
256    #[allow(dead_code)]
257    compositor_gpu: Option<CompositorGpuHint>,
258    state: RendererState,
259    surface_config: wgpu::SurfaceConfiguration,
260    atlas: Arc<WgpuAtlas>,
261    transparent_alpha_mode: wgpu::CompositeAlphaMode,
262    opaque_alpha_mode: wgpu::CompositeAlphaMode,
263    max_texture_size: u32,
264    is_bgr: bool,
265    failed_frame_count: u32,
266    device_errors: Arc<DeviceErrorState>,
267    observed_error_generation: u64,
268    last_surface_error: Option<String>,
269    needs_redraw: bool,
270}
271
272impl WgpuRenderer {
273    fn core(&self) -> Option<&WgpuRendererCore> {
274        match &self.state {
275            RendererState::Ready { core, .. } | RendererState::Unconfigured { core } => Some(core),
276            RendererState::Released => None,
277        }
278    }
279
280    fn core_mut(&mut self) -> Option<&mut WgpuRendererCore> {
281        match &mut self.state {
282            RendererState::Ready { core, .. } | RendererState::Unconfigured { core } => Some(core),
283            RendererState::Released => None,
284        }
285    }
286
287    /// Creates a new WgpuRenderer from raw window handles.
288    ///
289    /// The `gpu_context` is a shared reference that coordinates GPU context across
290    /// multiple windows. The first window to create a renderer will initialize the
291    /// context; subsequent windows will share it.
292    ///
293    /// # Safety
294    /// The caller must ensure that the window handle remains valid for the lifetime
295    /// of the returned renderer.
296    #[cfg(not(target_family = "wasm"))]
297    pub fn new<W>(
298        gpu_context: GpuContext,
299        window: &W,
300        config: WgpuSurfaceConfig,
301        compositor_gpu: Option<CompositorGpuHint>,
302    ) -> anyhow::Result<Self>
303    where
304        W: HasWindowHandle + HasDisplayHandle + std::fmt::Debug + Send + Sync + Clone + 'static,
305    {
306        let window_handle = window
307            .window_handle()
308            .map_err(|e| anyhow::anyhow!("Failed to get window handle: {e}"))?;
309
310        let target = wgpu::SurfaceTargetUnsafe::RawHandle {
311            // Fall back to the display handle already provided via InstanceDescriptor::display.
312            raw_display_handle: None,
313            raw_window_handle: window_handle.as_raw(),
314        };
315
316        // Use the existing context's instance if available, otherwise create a new one.
317        // The surface must be created with the same instance that will be used for
318        // adapter selection, otherwise wgpu will panic.
319        let instance = gpu_context
320            .borrow()
321            .as_ref()
322            .map(|ctx| ctx.instance.clone())
323            .unwrap_or_else(|| WgpuContext::instance(Some(Box::new(window.clone()))));
324
325        // Safety: The caller guarantees that the window handle is valid for the
326        // lifetime of this renderer. In practice, the RawWindow struct is created
327        // from the native window handles and the surface is dropped before the window.
328        let surface = unsafe {
329            instance
330                .create_surface_unsafe(target)
331                .map_err(|e| anyhow::anyhow!("Failed to create surface: {e}"))?
332        };
333
334        let mut ctx_ref = gpu_context.borrow_mut();
335        let surface_configured = ctx_ref.is_none();
336        let context = match ctx_ref.as_mut() {
337            Some(context) => {
338                context.check_compatible_with_surface(&surface)?;
339                context
340            }
341            None => ctx_ref.insert(WgpuContext::new(
342                instance,
343                &surface,
344                &config,
345                compositor_gpu,
346            )?),
347        };
348
349        let atlas = Arc::new(WgpuAtlas::from_context(context));
350
351        Self::new_internal(
352            Some(Rc::clone(&gpu_context)),
353            context,
354            surface,
355            config,
356            surface_configured,
357            compositor_gpu,
358            atlas,
359        )
360    }
361
362    #[cfg(target_family = "wasm")]
363    pub fn new_from_canvas(
364        context: &WgpuContext,
365        canvas: &web_sys::HtmlCanvasElement,
366        config: WgpuSurfaceConfig,
367    ) -> anyhow::Result<Self> {
368        let surface = context
369            .instance
370            .create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone()))
371            .map_err(|e| anyhow::anyhow!("Failed to create surface: {e}"))?;
372        Self::new_from_surface(context, surface, config)
373    }
374
375    #[cfg(target_family = "wasm")]
376    #[allow(clippy::arc_with_non_send_sync)]
377    pub fn new_from_surface(
378        context: &WgpuContext,
379        surface: wgpu::Surface<'static>,
380        config: WgpuSurfaceConfig,
381    ) -> anyhow::Result<Self> {
382        let atlas = Arc::new(WgpuAtlas::from_context(context));
383        Self::new_internal(None, context, surface, config, false, None, atlas)
384    }
385
386    /// Returns the surface configuration for `config`, along with the transparent and
387    /// opaque alpha modes that the surface supports.
388    pub(crate) fn surface_configuration(
389        surface: &wgpu::Surface<'_>,
390        adapter: &wgpu::Adapter,
391        device: &wgpu::Device,
392        config: &WgpuSurfaceConfig,
393    ) -> anyhow::Result<(
394        wgpu::SurfaceConfiguration,
395        wgpu::CompositeAlphaMode,
396        wgpu::CompositeAlphaMode,
397    )> {
398        let surface_caps = surface.get_capabilities(adapter);
399        let preferred_formats = [
400            wgpu::TextureFormat::Bgra8Unorm,
401            wgpu::TextureFormat::Rgba8Unorm,
402        ];
403        let surface_format = preferred_formats
404            .iter()
405            .find(|f| surface_caps.formats.contains(f))
406            .copied()
407            .or_else(|| {
408                surface_caps
409                    .formats
410                    .iter()
411                    .find(|format| !format.is_srgb())
412                    .copied()
413            })
414            .or_else(|| surface_caps.formats.first().copied())
415            .ok_or_else(|| {
416                anyhow::anyhow!(
417                    "Surface reports no supported texture formats for adapter {:?}",
418                    adapter.get_info().name
419                )
420            })?;
421
422        let pick_alpha_mode =
423            |preferences: &[wgpu::CompositeAlphaMode]| -> anyhow::Result<wgpu::CompositeAlphaMode> {
424                preferences
425                    .iter()
426                    .find(|p| surface_caps.alpha_modes.contains(p))
427                    .copied()
428                    .or_else(|| surface_caps.alpha_modes.first().copied())
429                    .ok_or_else(|| {
430                        anyhow::anyhow!(
431                            "Surface reports no supported alpha modes for adapter {:?}",
432                            adapter.get_info().name
433                        )
434                    })
435            };
436
437        let transparent_alpha_mode = pick_alpha_mode(&[
438            wgpu::CompositeAlphaMode::PreMultiplied,
439            wgpu::CompositeAlphaMode::Inherit,
440        ])?;
441
442        let opaque_alpha_mode = pick_alpha_mode(&[
443            wgpu::CompositeAlphaMode::Opaque,
444            wgpu::CompositeAlphaMode::Inherit,
445        ])?;
446
447        let alpha_mode = if config.transparent {
448            transparent_alpha_mode
449        } else {
450            opaque_alpha_mode
451        };
452
453        let max_texture_size = device.limits().max_texture_dimension_2d;
454
455        let requested_width = config.size.width.0 as u32;
456        let requested_height = config.size.height.0 as u32;
457        let clamped_width = requested_width.min(max_texture_size);
458        let clamped_height = requested_height.min(max_texture_size);
459
460        if clamped_width != requested_width || clamped_height != requested_height {
461            warn!(
462                "Requested surface size ({}, {}) exceeds maximum texture dimension {}. \
463                 Clamping to ({}, {}). Window content may not fill the entire window.",
464                requested_width, requested_height, max_texture_size, clamped_width, clamped_height
465            );
466        }
467
468        let surface_config = wgpu::SurfaceConfiguration {
469            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
470            format: surface_format,
471            color_space: wgpu::SurfaceColorSpace::Auto,
472            width: clamped_width.max(1),
473            height: clamped_height.max(1),
474            present_mode: config
475                .preferred_present_mode
476                .filter(|mode| surface_caps.present_modes.contains(mode))
477                .unwrap_or(wgpu::PresentMode::Fifo),
478            desired_maximum_frame_latency: 2,
479            alpha_mode,
480            view_formats: vec![],
481        };
482
483        Ok((surface_config, transparent_alpha_mode, opaque_alpha_mode))
484    }
485
486    fn new_internal(
487        gpu_context: Option<GpuContext>,
488        context: &WgpuContext,
489        surface: wgpu::Surface<'static>,
490        config: WgpuSurfaceConfig,
491        surface_configured: bool,
492        compositor_gpu: Option<CompositorGpuHint>,
493        atlas: Arc<WgpuAtlas>,
494    ) -> anyhow::Result<Self> {
495        let (surface_config, transparent_alpha_mode, opaque_alpha_mode) =
496            Self::surface_configuration(&surface, &context.adapter, &context.device, &config)?;
497        // Adapter selection configures the surface with this same configuration when it
498        // creates the context, so only configure it here when that did not happen.
499        if !surface_configured {
500            surface.configure(&context.device, &surface_config);
501        }
502
503        let surface_format = surface_config.format;
504        let alpha_mode = surface_config.alpha_mode;
505        let max_texture_size = context.device.limits().max_texture_dimension_2d;
506        let core = WgpuRendererCore::new(context, atlas.clone(), surface_format, alpha_mode);
507
508        Ok(Self {
509            context: gpu_context,
510            compositor_gpu,
511            state: RendererState::Ready { surface, core },
512            surface_config,
513            atlas,
514            transparent_alpha_mode,
515            opaque_alpha_mode,
516            max_texture_size,
517            is_bgr: false,
518            failed_frame_count: 0,
519            device_errors: Arc::clone(context.errors()),
520            observed_error_generation: 0,
521            last_surface_error: None,
522            needs_redraw: false,
523        })
524    }
525}
526
527impl WgpuRendererCore {
528    fn create_bind_group_layouts(
529        device: &wgpu::Device,
530        uses_webgl_instance_data: bool,
531    ) -> WgpuBindGroupLayouts {
532        let globals =
533            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
534                label: Some("globals_layout"),
535                entries: &[
536                    wgpu::BindGroupLayoutEntry {
537                        binding: 0,
538                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
539                        ty: wgpu::BindingType::Buffer {
540                            ty: wgpu::BufferBindingType::Uniform,
541                            has_dynamic_offset: false,
542                            min_binding_size: NonZeroU64::new(
543                                std::mem::size_of::<GlobalParams>() as u64
544                            ),
545                        },
546                        count: None,
547                    },
548                    wgpu::BindGroupLayoutEntry {
549                        binding: 1,
550                        visibility: wgpu::ShaderStages::FRAGMENT,
551                        ty: wgpu::BindingType::Buffer {
552                            ty: wgpu::BufferBindingType::Uniform,
553                            has_dynamic_offset: false,
554                            min_binding_size: NonZeroU64::new(
555                                std::mem::size_of::<GammaParams>() as u64
556                            ),
557                        },
558                        count: None,
559                    },
560                ],
561            });
562
563        let instance_data_entry = wgpu::BindGroupLayoutEntry {
564            binding: 0,
565            visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
566            ty: if uses_webgl_instance_data {
567                wgpu::BindingType::Texture {
568                    sample_type: wgpu::TextureSampleType::Uint,
569                    view_dimension: wgpu::TextureViewDimension::D2,
570                    multisampled: false,
571                }
572            } else {
573                wgpu::BindingType::Buffer {
574                    ty: wgpu::BufferBindingType::Storage { read_only: true },
575                    has_dynamic_offset: false,
576                    min_binding_size: None,
577                }
578            },
579            count: None,
580        };
581
582        let instances = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
583            label: Some("instances_layout"),
584            entries: &[instance_data_entry],
585        });
586
587        // Path tiles read their curves and paints too. The texture transport
588        // reads all three from the one instance texture.
589        let path_tiles = if uses_webgl_instance_data {
590            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
591                label: Some("path_tiles_layout"),
592                entries: &[instance_data_entry],
593            })
594        } else {
595            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
596                label: Some("path_tiles_layout"),
597                entries: &[
598                    instance_data_entry,
599                    wgpu::BindGroupLayoutEntry {
600                        binding: 1,
601                        ..instance_data_entry
602                    },
603                    wgpu::BindGroupLayoutEntry {
604                        binding: 2,
605                        ..instance_data_entry
606                    },
607                ],
608            })
609        };
610
611        let texture = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
612            label: Some("texture_layout"),
613            entries: &[
614                wgpu::BindGroupLayoutEntry {
615                    binding: 0,
616                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
617                    ty: wgpu::BindingType::Texture {
618                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
619                        view_dimension: wgpu::TextureViewDimension::D2,
620                        multisampled: false,
621                    },
622                    count: None,
623                },
624                wgpu::BindGroupLayoutEntry {
625                    binding: 1,
626                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
627                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
628                    count: None,
629                },
630            ],
631        });
632
633        let surfaces = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
634            label: Some("surfaces_layout"),
635            entries: &[
636                wgpu::BindGroupLayoutEntry {
637                    binding: 0,
638                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
639                    ty: wgpu::BindingType::Buffer {
640                        ty: wgpu::BufferBindingType::Uniform,
641                        has_dynamic_offset: false,
642                        min_binding_size: NonZeroU64::new(
643                            std::mem::size_of::<SurfaceParams>() as u64
644                        ),
645                    },
646                    count: None,
647                },
648                wgpu::BindGroupLayoutEntry {
649                    binding: 1,
650                    visibility: wgpu::ShaderStages::FRAGMENT,
651                    ty: wgpu::BindingType::Texture {
652                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
653                        view_dimension: wgpu::TextureViewDimension::D2,
654                        multisampled: false,
655                    },
656                    count: None,
657                },
658                wgpu::BindGroupLayoutEntry {
659                    binding: 2,
660                    visibility: wgpu::ShaderStages::FRAGMENT,
661                    ty: wgpu::BindingType::Texture {
662                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
663                        view_dimension: wgpu::TextureViewDimension::D2,
664                        multisampled: false,
665                    },
666                    count: None,
667                },
668                wgpu::BindGroupLayoutEntry {
669                    binding: 3,
670                    visibility: wgpu::ShaderStages::FRAGMENT,
671                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
672                    count: None,
673                },
674            ],
675        });
676
677        WgpuBindGroupLayouts {
678            globals,
679            instances,
680            path_tiles,
681            texture,
682            surfaces,
683        }
684    }
685
686    fn create_instance_texture(
687        device: &wgpu::Device,
688        requested_capacity: u64,
689        max_texture_dimension: u32,
690    ) -> (InstanceData, u64) {
691        let texel_count = requested_capacity.div_ceil(INSTANCE_TEXTURE_TEXEL_SIZE);
692        let width = texel_count.min(u64::from(max_texture_dimension)).max(1) as u32;
693        let height = texel_count
694            .div_ceil(u64::from(width))
695            .min(u64::from(max_texture_dimension))
696            .max(1) as u32;
697        let texture = device.create_texture(&wgpu::TextureDescriptor {
698            label: Some("instance_texture"),
699            size: wgpu::Extent3d {
700                width,
701                height,
702                depth_or_array_layers: 1,
703            },
704            mip_level_count: 1,
705            sample_count: 1,
706            dimension: wgpu::TextureDimension::D2,
707            format: wgpu::TextureFormat::Rgba32Uint,
708            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
709            view_formats: &[],
710        });
711        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
712        let capacity = u64::from(width) * u64::from(height) * INSTANCE_TEXTURE_TEXEL_SIZE;
713        (
714            InstanceData::Texture {
715                texture,
716                view,
717                width,
718                height,
719            },
720            capacity,
721        )
722    }
723
724    fn create_pipelines(
725        device: &wgpu::Device,
726        layouts: &WgpuBindGroupLayouts,
727        surface_format: wgpu::TextureFormat,
728        alpha_mode: wgpu::CompositeAlphaMode,
729        dual_source_blending: bool,
730        uses_webgl_instance_data: bool,
731    ) -> WgpuPipelines {
732        // Diagnostic guard: verify the device actually has
733        // DUAL_SOURCE_BLENDING. We have a crash report (ZED-5G1) where a
734        // feature mismatch caused a wgpu-hal abort, but we haven't
735        // identified the code path that produces the mismatch. This
736        // guard prevents the crash and logs more evidence.
737        // Remove this check once:
738        // a) We find and fix the root cause, or
739        // b) There are no reports of this warning appearing for some time.
740        let device_has_feature = device
741            .features()
742            .contains(wgpu::Features::DUAL_SOURCE_BLENDING);
743        if dual_source_blending && !device_has_feature {
744            log::error!(
745                "BUG: dual_source_blending flag is true but device does not \
746                 have DUAL_SOURCE_BLENDING enabled (device features: {:?}). \
747                 Falling back to mono text rendering. Please report this at \
748                 https://github.com/zed-industries/zed/issues",
749                device.features(),
750            );
751        }
752        let dual_source_blending =
753            dual_source_blending && device_has_feature && !uses_webgl_instance_data;
754
755        let shader_source = if uses_webgl_instance_data {
756            WEBGL_SHADERS
757        } else {
758            STORAGE_BUFFER_SHADERS
759        };
760        let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
761            label: Some("gpui_shaders"),
762            source: wgpu::ShaderSource::Wgsl(shader_source.into()),
763        });
764
765        let subpixel_shader_module = if dual_source_blending {
766            Some(device.create_shader_module(wgpu::ShaderModuleDescriptor {
767                label: Some("gpui_subpixel_shaders"),
768                source: wgpu::ShaderSource::Wgsl(SUBPIXEL_SHADERS.into()),
769            }))
770        } else {
771            None
772        };
773
774        let premultiplied_alpha = alpha_mode == wgpu::CompositeAlphaMode::PreMultiplied;
775        let blend_mode = if premultiplied_alpha {
776            wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING
777        } else {
778            wgpu::BlendState::ALPHA_BLENDING
779        };
780
781        let color_target = wgpu::ColorTargetState {
782            format: surface_format,
783            blend: Some(blend_mode),
784            write_mask: wgpu::ColorWrites::ALL,
785        };
786
787        let create_pipeline = |name: &str,
788                               vs_entry: &str,
789                               fs_entry: &str,
790                               globals_layout: &wgpu::BindGroupLayout,
791                               data_layout: &wgpu::BindGroupLayout,
792                               texture_layout: Option<&wgpu::BindGroupLayout>,
793                               topology: wgpu::PrimitiveTopology,
794                               color_targets: &[Option<wgpu::ColorTargetState>],
795                               depth_write_enabled: bool,
796                               module: &wgpu::ShaderModule| {
797            let mut bind_group_layouts = vec![Some(globals_layout), Some(data_layout)];
798            bind_group_layouts.extend(texture_layout.map(Some));
799            let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
800                label: Some(&format!("{name}_layout")),
801                bind_group_layouts: &bind_group_layouts,
802                immediate_size: 0,
803            });
804
805            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
806                label: Some(name),
807                layout: Some(&pipeline_layout),
808                vertex: wgpu::VertexState {
809                    module,
810                    entry_point: Some(vs_entry),
811                    buffers: &[],
812                    compilation_options: wgpu::PipelineCompilationOptions::default(),
813                },
814                fragment: Some(wgpu::FragmentState {
815                    module,
816                    entry_point: Some(fs_entry),
817                    targets: color_targets,
818                    compilation_options: wgpu::PipelineCompilationOptions::default(),
819                }),
820                primitive: wgpu::PrimitiveState {
821                    topology,
822                    strip_index_format: None,
823                    front_face: wgpu::FrontFace::Ccw,
824                    cull_mode: None,
825                    polygon_mode: wgpu::PolygonMode::Fill,
826                    unclipped_depth: false,
827                    conservative: false,
828                },
829                depth_stencil: Some(wgpu::DepthStencilState {
830                    format: DEPTH_FORMAT,
831                    depth_write_enabled: Some(depth_write_enabled),
832                    depth_compare: Some(wgpu::CompareFunction::Greater),
833                    stencil: wgpu::StencilState::default(),
834                    bias: wgpu::DepthBiasState::default(),
835                }),
836                multisample: wgpu::MultisampleState::default(),
837                multiview_mask: None,
838                cache: None,
839            })
840        };
841
842        let quads = create_pipeline(
843            "quads",
844            "vs_quad",
845            "fs_quad",
846            &layouts.globals,
847            &layouts.instances,
848            None,
849            wgpu::PrimitiveTopology::TriangleStrip,
850            &[Some(color_target.clone())],
851            false,
852            &shader_module,
853        );
854
855        let opaque_quads = create_pipeline(
856            "opaque_quads",
857            "vs_opaque_quad",
858            "fs_opaque_quad",
859            &layouts.globals,
860            &layouts.instances,
861            None,
862            wgpu::PrimitiveTopology::TriangleStrip,
863            &[Some(wgpu::ColorTargetState {
864                format: surface_format,
865                blend: None,
866                write_mask: wgpu::ColorWrites::ALL,
867            })],
868            true,
869            &shader_module,
870        );
871
872        let shadows = create_pipeline(
873            "shadows",
874            "vs_shadow",
875            "fs_shadow",
876            &layouts.globals,
877            &layouts.instances,
878            None,
879            wgpu::PrimitiveTopology::TriangleStrip,
880            &[Some(color_target.clone())],
881            false,
882            &shader_module,
883        );
884
885        let path_tiles = create_pipeline(
886            "path_tiles",
887            "vs_path_tile",
888            "fs_path_tile",
889            &layouts.globals,
890            &layouts.path_tiles,
891            None,
892            wgpu::PrimitiveTopology::TriangleStrip,
893            &[Some(color_target.clone())],
894            false,
895            &shader_module,
896        );
897
898        let underlines = create_pipeline(
899            "underlines",
900            "vs_underline",
901            "fs_underline",
902            &layouts.globals,
903            &layouts.instances,
904            None,
905            wgpu::PrimitiveTopology::TriangleStrip,
906            &[Some(color_target.clone())],
907            false,
908            &shader_module,
909        );
910
911        let mono_sprites = create_pipeline(
912            "mono_sprites",
913            "vs_mono_sprite",
914            "fs_mono_sprite",
915            &layouts.globals,
916            &layouts.instances,
917            Some(&layouts.texture),
918            wgpu::PrimitiveTopology::TriangleStrip,
919            &[Some(color_target.clone())],
920            false,
921            &shader_module,
922        );
923
924        let subpixel_sprites = if let Some(subpixel_module) = &subpixel_shader_module {
925            let subpixel_blend = wgpu::BlendState {
926                color: wgpu::BlendComponent {
927                    src_factor: wgpu::BlendFactor::Src1,
928                    dst_factor: wgpu::BlendFactor::OneMinusSrc1,
929                    operation: wgpu::BlendOperation::Add,
930                },
931                alpha: wgpu::BlendComponent {
932                    src_factor: wgpu::BlendFactor::One,
933                    dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
934                    operation: wgpu::BlendOperation::Add,
935                },
936            };
937
938            Some(create_pipeline(
939                "subpixel_sprites",
940                "vs_subpixel_sprite",
941                "fs_subpixel_sprite",
942                &layouts.globals,
943                &layouts.instances,
944                Some(&layouts.texture),
945                wgpu::PrimitiveTopology::TriangleStrip,
946                &[Some(wgpu::ColorTargetState {
947                    format: surface_format,
948                    blend: Some(subpixel_blend),
949                    write_mask: wgpu::ColorWrites::COLOR,
950                })],
951                false,
952                subpixel_module,
953            ))
954        } else {
955            None
956        };
957
958        let poly_sprites = create_pipeline(
959            "poly_sprites",
960            "vs_poly_sprite",
961            "fs_poly_sprite",
962            &layouts.globals,
963            &layouts.instances,
964            Some(&layouts.texture),
965            wgpu::PrimitiveTopology::TriangleStrip,
966            &[Some(color_target.clone())],
967            false,
968            &shader_module,
969        );
970
971        let surfaces = create_pipeline(
972            "surfaces",
973            "vs_surface",
974            "fs_surface",
975            &layouts.globals,
976            &layouts.surfaces,
977            None,
978            wgpu::PrimitiveTopology::TriangleStrip,
979            &[Some(color_target)],
980            false,
981            &shader_module,
982        );
983
984        WgpuPipelines {
985            quads,
986            opaque_quads,
987            shadows,
988            path_tiles,
989            underlines,
990            mono_sprites,
991            subpixel_sprites,
992            poly_sprites,
993            surfaces,
994            premultiplied_alpha,
995        }
996    }
997}
998
999impl WgpuRenderer {
1000    /// Records the new drawable size and reconfigures the surface when one is present.
1001    /// The size is kept even without GPU resources so that recovery restores it.
1002    pub fn update_drawable_size(&mut self, size: Size<DevicePixels>) {
1003        let width = size.width.0 as u32;
1004        let height = size.height.0 as u32;
1005
1006        if width == self.surface_config.width && height == self.surface_config.height {
1007            return;
1008        }
1009
1010        let clamped_width = width.min(self.max_texture_size);
1011        let clamped_height = height.min(self.max_texture_size);
1012        if clamped_width != width || clamped_height != height {
1013            warn!(
1014                "Requested surface size ({}, {}) exceeds maximum texture dimension {}. \
1015                 Clamping to ({}, {}). Window content may not fill the entire window.",
1016                width, height, self.max_texture_size, clamped_width, clamped_height
1017            );
1018        }
1019        self.surface_config.width = clamped_width.max(1);
1020        self.surface_config.height = clamped_height.max(1);
1021
1022        if let RendererState::Ready { surface, core } = &self.state {
1023            surface.configure(&core.resources.device, &self.surface_config);
1024        }
1025    }
1026
1027    pub fn set_subpixel_layout(&mut self, is_bgr: bool) {
1028        self.is_bgr = is_bgr;
1029        if let Some(core) = self.core_mut() {
1030            core.is_bgr = is_bgr;
1031        }
1032    }
1033
1034    pub fn update_transparency(&mut self, transparent: bool) {
1035        let new_alpha_mode = if transparent {
1036            self.transparent_alpha_mode
1037        } else {
1038            self.opaque_alpha_mode
1039        };
1040        if new_alpha_mode == self.surface_config.alpha_mode {
1041            return;
1042        }
1043        self.surface_config.alpha_mode = new_alpha_mode;
1044        let format = self.surface_config.format;
1045
1046        let Some(core) = self.core_mut() else {
1047            return;
1048        };
1049        core.rebuild_pipelines(format, new_alpha_mode);
1050
1051        if let RendererState::Ready { surface, core } = &self.state {
1052            surface.configure(&core.resources.device, &self.surface_config);
1053        }
1054    }
1055
1056    #[allow(dead_code)]
1057    pub fn viewport_size(&self) -> Size<DevicePixels> {
1058        Size {
1059            width: DevicePixels(self.surface_config.width as i32),
1060            height: DevicePixels(self.surface_config.height as i32),
1061        }
1062    }
1063
1064    pub fn sprite_atlas(&self) -> &Arc<WgpuAtlas> {
1065        &self.atlas
1066    }
1067
1068    pub fn supports_dual_source_blending(&self) -> bool {
1069        self.core().is_some_and(|core| core.dual_source_blending)
1070    }
1071
1072    /// Returns `None` once GPU resources have been released by `destroy` or a pending
1073    /// device recovery.
1074    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
1075        let adapter_info = &self.core()?.adapter_info;
1076        Some(GpuSpecs {
1077            is_software_emulated: adapter_info.device_type == wgpu::DeviceType::Cpu,
1078            device_name: adapter_info.name.clone(),
1079            driver_name: adapter_info.driver.clone(),
1080            driver_info: adapter_info.driver_info.clone(),
1081        })
1082    }
1083
1084    pub fn max_texture_size(&self) -> u32 {
1085        self.max_texture_size
1086    }
1087
1088    pub fn draw(&mut self, scene: &Scene) -> bool {
1089        #[cfg(target_family = "wasm")]
1090        if self.device_lost() {
1091            if matches!(self.state, RendererState::Ready { .. }) {
1092                log::error!(
1093                    "Browser graphics context was lost; rendering has stopped. Reload the page to recover."
1094                );
1095                self.unconfigure_surface();
1096            }
1097            return false;
1098        }
1099
1100        // Bail out early if the surface has been unconfigured (e.g. during
1101        // Android background/rotation transitions).  Attempting to acquire
1102        // a texture from an unconfigured surface can block indefinitely on
1103        // some drivers (Adreno).
1104        let RendererState::Ready { surface, core } = &mut self.state else {
1105            return false;
1106        };
1107
1108        if let Some(error) = self.last_surface_error.take().or_else(|| {
1109            self.device_errors
1110                .observe_error(&mut self.observed_error_generation)
1111        }) {
1112            self.failed_frame_count += 1;
1113            log::error!(
1114                "GPU error during frame (failure {} of 10): {error}",
1115                self.failed_frame_count
1116            );
1117
1118            // TBD. Does retrying more actually help?
1119            if self.failed_frame_count > 10 {
1120                panic!("Too many consecutive GPU errors. Last error: {error}");
1121            } else if self.failed_frame_count > 5 {
1122                self.atlas.clear();
1123                self.needs_redraw = true;
1124                self.failed_frame_count = 0;
1125                return false;
1126            }
1127        } else {
1128            self.failed_frame_count = 0;
1129        }
1130
1131        let frame = match surface.get_current_texture() {
1132            wgpu::CurrentSurfaceTexture::Success(frame) => frame,
1133            wgpu::CurrentSurfaceTexture::Suboptimal(frame) => {
1134                // Textures must be destroyed before the surface can be reconfigured.
1135                drop(frame);
1136                surface.configure(&core.resources.device, &self.surface_config);
1137                return false;
1138            }
1139            wgpu::CurrentSurfaceTexture::Lost | wgpu::CurrentSurfaceTexture::Outdated => {
1140                surface.configure(&core.resources.device, &self.surface_config);
1141                return false;
1142            }
1143            wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
1144                return false;
1145            }
1146            wgpu::CurrentSurfaceTexture::Validation => {
1147                self.last_surface_error = Some("Surface texture validation error".to_string());
1148                return false;
1149            }
1150        };
1151
1152        // The acquired texture is the authority on frame dimensions; the surface
1153        // configuration is only a request.
1154        let size = Size {
1155            width: DevicePixels(frame.texture.width() as i32),
1156            height: DevicePixels(frame.texture.height() as i32),
1157        };
1158        let frame_view = frame
1159            .texture
1160            .create_view(&wgpu::TextureViewDescriptor::default());
1161        if let Err(error) = core.render_frame(scene, &frame_view, size, wgpu::Color::TRANSPARENT) {
1162            log::error!("{error:#}");
1163            return false;
1164        }
1165
1166        core.resources.queue.present(frame);
1167        true
1168    }
1169}
1170
1171impl WgpuRendererCore {
1172    fn new(
1173        context: &WgpuContext,
1174        atlas: Arc<WgpuAtlas>,
1175        target_format: wgpu::TextureFormat,
1176        alpha_mode: wgpu::CompositeAlphaMode,
1177    ) -> Self {
1178        let device = Arc::clone(&context.device);
1179        let queue = Arc::clone(&context.queue);
1180        let rendering_params = RenderingParameters::new();
1181        let uses_webgl_instance_data = context.uses_webgl_instance_data();
1182        let dual_source_blending =
1183            context.supports_dual_source_blending() && !uses_webgl_instance_data;
1184        let bind_group_layouts = Self::create_bind_group_layouts(&device, uses_webgl_instance_data);
1185        let pipelines = Self::create_pipelines(
1186            &device,
1187            &bind_group_layouts,
1188            target_format,
1189            alpha_mode,
1190            dual_source_blending,
1191            uses_webgl_instance_data,
1192        );
1193        let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
1194            label: Some("atlas_sampler"),
1195            mag_filter: wgpu::FilterMode::Linear,
1196            min_filter: wgpu::FilterMode::Linear,
1197            ..Default::default()
1198        });
1199        let uniform_alignment = device.limits().min_uniform_buffer_offset_alignment as u64;
1200        let globals_size = std::mem::size_of::<GlobalParams>() as u64;
1201        let gamma_size = std::mem::size_of::<GammaParams>() as u64;
1202        let gamma_offset = globals_size.next_multiple_of(uniform_alignment);
1203        let globals_buffer = device.create_buffer(&wgpu::BufferDescriptor {
1204            label: Some("globals_buffer"),
1205            size: gamma_offset + gamma_size,
1206            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1207            mapped_at_creation: false,
1208        });
1209        let (
1210            instance_data,
1211            instance_data_capacity,
1212            max_instance_data_size,
1213            instance_data_alignment,
1214        ) = if uses_webgl_instance_data {
1215            let max_texture_dimension = device.limits().max_texture_dimension_2d;
1216            let max_instance_data_size = (u64::from(max_texture_dimension).pow(2)
1217                * INSTANCE_TEXTURE_TEXEL_SIZE)
1218                .min(MAX_INSTANCE_BUFFER_SIZE);
1219            let initial_capacity = (2 * 1024 * 1024).min(max_instance_data_size);
1220            let (instance_data, capacity) =
1221                Self::create_instance_texture(&device, initial_capacity, max_texture_dimension);
1222            (
1223                instance_data,
1224                capacity,
1225                max_instance_data_size,
1226                INSTANCE_TEXTURE_TEXEL_SIZE,
1227            )
1228        } else {
1229            let max_buffer_size = device
1230                .limits()
1231                .max_buffer_size
1232                .min(device.limits().max_storage_buffer_binding_size)
1233                .min(MAX_INSTANCE_BUFFER_SIZE);
1234            let initial_capacity = (2 * 1024 * 1024).min(max_buffer_size);
1235            let buffer = device.create_buffer(&wgpu::BufferDescriptor {
1236                label: Some("instance_buffer"),
1237                size: initial_capacity,
1238                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
1239                mapped_at_creation: false,
1240            });
1241            (
1242                InstanceData::Storage(buffer),
1243                initial_capacity,
1244                max_buffer_size,
1245                device.limits().min_storage_buffer_offset_alignment as u64,
1246            )
1247        };
1248        let globals_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
1249            label: Some("globals_bind_group"),
1250            layout: &bind_group_layouts.globals,
1251            entries: &[
1252                wgpu::BindGroupEntry {
1253                    binding: 0,
1254                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
1255                        buffer: &globals_buffer,
1256                        offset: 0,
1257                        size: NonZeroU64::new(globals_size),
1258                    }),
1259                },
1260                wgpu::BindGroupEntry {
1261                    binding: 1,
1262                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
1263                        buffer: &globals_buffer,
1264                        offset: gamma_offset,
1265                        size: NonZeroU64::new(gamma_size),
1266                    }),
1267                },
1268            ],
1269        });
1270        let max_texture_size = device.limits().max_texture_dimension_2d;
1271
1272        Self {
1273            resources: WgpuResources {
1274                device,
1275                queue,
1276                pipelines,
1277                bind_group_layouts,
1278                atlas_sampler,
1279                atlas_texture_bind_groups: FxHashMap::default(),
1280                globals_buffer,
1281                globals_bind_group,
1282                instance_data,
1283            },
1284            atlas,
1285            gamma_offset,
1286            instance_data_capacity,
1287            max_instance_data_size,
1288            instance_data_alignment,
1289            uses_webgl_instance_data,
1290            rendering_params,
1291            is_bgr: false,
1292            dual_source_blending,
1293            transient_attachments: context.supports_transient_attachments(),
1294            adapter_info: context.adapter.get_info(),
1295            depth_texture: None,
1296            #[cfg(all(
1297                not(target_family = "wasm"),
1298                any(test, feature = "bench-support", feature = "test-support")
1299            ))]
1300            target_format,
1301            max_texture_size,
1302        }
1303    }
1304
1305    fn resources(&self) -> &WgpuResources {
1306        &self.resources
1307    }
1308
1309    fn rebuild_pipelines(
1310        &mut self,
1311        surface_format: wgpu::TextureFormat,
1312        alpha_mode: wgpu::CompositeAlphaMode,
1313    ) {
1314        self.resources.pipelines = Self::create_pipelines(
1315            &self.resources.device,
1316            &self.resources.bind_group_layouts,
1317            surface_format,
1318            alpha_mode,
1319            self.dual_source_blending,
1320            self.uses_webgl_instance_data,
1321        );
1322    }
1323
1324    fn resources_mut(&mut self) -> &mut WgpuResources {
1325        &mut self.resources
1326    }
1327
1328    fn render_frame(
1329        &mut self,
1330        scene: &Scene,
1331        target_view: &wgpu::TextureView,
1332        size: Size<DevicePixels>,
1333        clear_color: wgpu::Color,
1334    ) -> Result<wgpu::SubmissionIndex> {
1335        anyhow::ensure!(
1336            size.width.0 > 0 && size.height.0 > 0,
1337            "invalid render target size: {size:?}"
1338        );
1339        anyhow::ensure!(
1340            size.width.0 as u32 <= self.max_texture_size
1341                && size.height.0 as u32 <= self.max_texture_size,
1342            "render target size {size:?} exceeds maximum texture dimension {}",
1343            self.max_texture_size
1344        );
1345
1346        self.atlas.before_frame();
1347
1348        let gamma_params = GammaParams {
1349            gamma_ratios: self.rendering_params.gamma_ratios,
1350            grayscale_enhanced_contrast: self.rendering_params.grayscale_enhanced_contrast,
1351            subpixel_enhanced_contrast: self.rendering_params.subpixel_enhanced_contrast,
1352            is_bgr: self.is_bgr as u32,
1353            _pad: 0,
1354        };
1355        self.resources.queue.write_buffer(
1356            &self.resources.globals_buffer,
1357            self.gamma_offset,
1358            bytemuck::bytes_of(&gamma_params),
1359        );
1360
1361        self.record_frame(scene, target_view, size, clear_color)
1362            .inspect_err(|_| {
1363                // Queue writes are staged before encoding; flush them even if the frame fails.
1364                self.resources.queue.submit(std::iter::empty());
1365            })
1366    }
1367
1368    fn record_frame(
1369        &mut self,
1370        scene: &Scene,
1371        frame_view: &wgpu::TextureView,
1372        size: Size<DevicePixels>,
1373        clear_color: wgpu::Color,
1374    ) -> Result<wgpu::SubmissionIndex> {
1375        let mut instance_offset = 0;
1376        let instance_bindings = self
1377            .write_instances(scene, &mut instance_offset)
1378            .with_context(|| {
1379                format!(
1380                    "scene too large: {} paths, {} shadows, {} quads, {} underlines, {} monochrome sprites, {} subpixel sprites, {} polychrome sprites",
1381                    scene.paths.len(),
1382                    scene.shadows.len(),
1383                    scene.quads.len(),
1384                    scene.underlines.len(),
1385                    scene.monochrome_sprites.len(),
1386                    scene.subpixel_sprites.len(),
1387                    scene.polychrome_sprites.len(),
1388                )
1389            })?;
1390        let depth_scale = quad_depth_scale(scene.quads.len());
1391        let globals = GlobalParams {
1392            viewport_size: [size.width.0 as f32, size.height.0 as f32],
1393            path_paint_base: instance_bindings.path_tiles.paint_base,
1394            path_curve_base: instance_bindings.path_tiles.curve_base,
1395            depth_scale,
1396            quad_count: scene.quads.len() as u32,
1397            premultiplied_alpha: self.resources().pipelines.premultiplied_alpha as u32,
1398            pad: 0,
1399        };
1400        self.resources().queue.write_buffer(
1401            &self.resources().globals_buffer,
1402            0,
1403            bytemuck::bytes_of(&globals),
1404        );
1405        self.prepare_texture_bind_groups(scene);
1406        self.ensure_depth_texture(size);
1407        let depth_view = &self
1408            .depth_texture
1409            .as_ref()
1410            .context("depth texture missing")?
1411            .view;
1412        // Quads are written first, so their instance indices are their
1413        // indices in `scene.quads` on both transports, which the quad depths
1414        // rely on.
1415        debug_assert_eq!(instance_bindings.quads.first_instance, 0);
1416
1417        let mut encoder =
1418            self.resources()
1419                .device
1420                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1421                    label: Some("main_encoder"),
1422                });
1423
1424        {
1425            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1426                label: Some("main_pass"),
1427                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1428                    view: frame_view,
1429                    resolve_target: None,
1430                    ops: wgpu::Operations {
1431                        load: wgpu::LoadOp::Clear(clear_color),
1432                        store: wgpu::StoreOp::Store,
1433                    },
1434                    depth_slice: None,
1435                })],
1436                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
1437                    view: depth_view,
1438                    depth_ops: Some(wgpu::Operations {
1439                        load: wgpu::LoadOp::Clear(0.0),
1440                        store: wgpu::StoreOp::Discard,
1441                    }),
1442                    stencil_ops: None,
1443                }),
1444                ..Default::default()
1445            });
1446            pass.set_bind_group(0, &self.resources().globals_bind_group, &[]);
1447
1448            self.draw_instances(
1449                &instance_bindings.quads,
1450                &self.resources().pipelines.opaque_quads,
1451                instance_range(0..scene.quads.len()),
1452                &mut pass,
1453            );
1454
1455            let viewport_width = size.width.0 as f32;
1456            let viewport_height = size.height.0 as f32;
1457            let mut quad_cursor: u32 = 0;
1458            let mut path_tile_cursor = 0;
1459            for batch in scene.batches() {
1460                // Quad shaders assign each quad its own depth.
1461                // In every other batch type, the depth is fixed to the position of the quad cursor.
1462                let (minimum_depth, maximum_depth) = if matches!(&batch, PrimitiveBatch::Quads(_)) {
1463                    (0.0, 1.0)
1464                } else {
1465                    let depth = quad_depth(quad_cursor, depth_scale);
1466                    (depth, depth)
1467                };
1468                pass.set_viewport(
1469                    0.0,
1470                    0.0,
1471                    viewport_width,
1472                    viewport_height,
1473                    minimum_depth,
1474                    maximum_depth,
1475                );
1476
1477                match batch {
1478                    PrimitiveBatch::Quads(range) => {
1479                        quad_cursor += range.len() as u32;
1480                        self.draw_instances(
1481                            &instance_bindings.quads,
1482                            &self.resources().pipelines.quads,
1483                            instance_range(range),
1484                            &mut pass,
1485                        )
1486                    }
1487                    PrimitiveBatch::Shadows(range) => self.draw_instances(
1488                        &instance_bindings.shadows,
1489                        &self.resources().pipelines.shadows,
1490                        instance_range(range),
1491                        &mut pass,
1492                    ),
1493                    PrimitiveBatch::Paths(range) => {
1494                        let tiles_start = path_tile_cursor;
1495                        path_tile_cursor += scene.paths[range]
1496                            .iter()
1497                            .map(PaintedPath::tile_count)
1498                            .sum::<usize>();
1499                        self.draw_instances(
1500                            &instance_bindings.path_tiles.tiles,
1501                            &self.resources().pipelines.path_tiles,
1502                            instance_range(tiles_start..path_tile_cursor),
1503                            &mut pass,
1504                        )
1505                    }
1506                    PrimitiveBatch::Underlines(range) => self.draw_instances(
1507                        &instance_bindings.underlines,
1508                        &self.resources().pipelines.underlines,
1509                        instance_range(range),
1510                        &mut pass,
1511                    ),
1512                    PrimitiveBatch::MonochromeSprites { texture_id, range } => {
1513                        self.draw_sprites(
1514                            &instance_bindings.monochrome_sprites,
1515                            texture_id,
1516                            &self.resources().pipelines.mono_sprites,
1517                            instance_range(range),
1518                            &mut pass,
1519                        )?;
1520                    }
1521                    PrimitiveBatch::SubpixelSprites { texture_id, range } => {
1522                        let resources = self.resources();
1523                        self.draw_sprites(
1524                            &instance_bindings.subpixel_sprites,
1525                            texture_id,
1526                            resources
1527                                .pipelines
1528                                .subpixel_sprites
1529                                .as_ref()
1530                                .unwrap_or(&resources.pipelines.mono_sprites),
1531                            instance_range(range),
1532                            &mut pass,
1533                        )?;
1534                    }
1535                    PrimitiveBatch::PolychromeSprites { texture_id, range } => {
1536                        self.draw_sprites(
1537                            &instance_bindings.polychrome_sprites,
1538                            texture_id,
1539                            &self.resources().pipelines.poly_sprites,
1540                            instance_range(range),
1541                            &mut pass,
1542                        )?;
1543                    }
1544                    // Surfaces are macOS-only for video playback and are not
1545                    // implemented by the WGPU renderer.
1546                    PrimitiveBatch::Surfaces(_surfaces) => {}
1547                }
1548            }
1549        }
1550
1551        let submission = self
1552            .resources()
1553            .queue
1554            .submit(std::iter::once(encoder.finish()));
1555        Ok(submission)
1556    }
1557
1558    fn ensure_depth_texture(&mut self, size: Size<DevicePixels>) {
1559        let width = size.width.0 as u32;
1560        let height = size.height.0 as u32;
1561        if let Some(depth_texture) = &self.depth_texture
1562            && depth_texture.texture.width() == width
1563            && depth_texture.texture.height() == height
1564        {
1565            return;
1566        }
1567        let usage = if self.transient_attachments {
1568            wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TRANSIENT_ATTACHMENT
1569        } else {
1570            wgpu::TextureUsages::RENDER_ATTACHMENT
1571        };
1572        let texture = self
1573            .resources()
1574            .device
1575            .create_texture(&wgpu::TextureDescriptor {
1576                label: Some("depth_texture"),
1577                size: wgpu::Extent3d {
1578                    width,
1579                    height,
1580                    depth_or_array_layers: 1,
1581                },
1582                mip_level_count: 1,
1583                sample_count: 1,
1584                dimension: wgpu::TextureDimension::D2,
1585                format: DEPTH_FORMAT,
1586                usage,
1587                view_formats: &[],
1588            });
1589        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
1590        self.depth_texture = Some(DepthTexture { texture, view });
1591    }
1592
1593    fn write_instances(
1594        &mut self,
1595        scene: &Scene,
1596        instance_offset: &mut u64,
1597    ) -> Result<InstanceBindings> {
1598        Ok(InstanceBindings {
1599            quads: self.write_instance_binding(
1600                "quads_bind_group",
1601                instance_offset,
1602                &scene.quads,
1603            )?,
1604            shadows: self.write_instance_binding(
1605                "shadows_bind_group",
1606                instance_offset,
1607                &scene.shadows,
1608            )?,
1609            path_tiles: self.write_path_tiles(scene, instance_offset)?,
1610            underlines: self.write_instance_binding(
1611                "underlines_bind_group",
1612                instance_offset,
1613                &scene.underlines,
1614            )?,
1615            monochrome_sprites: self.write_instance_binding(
1616                "monochrome_sprites_bind_group",
1617                instance_offset,
1618                &scene.monochrome_sprites,
1619            )?,
1620            subpixel_sprites: self.write_instance_binding(
1621                "subpixel_sprites_bind_group",
1622                instance_offset,
1623                &scene.subpixel_sprites,
1624            )?,
1625            polychrome_sprites: self.write_instance_binding(
1626                "polychrome_sprites_bind_group",
1627                instance_offset,
1628                &scene.polychrome_sprites,
1629            )?,
1630        })
1631    }
1632
1633    fn create_texture_bind_group(
1634        &self,
1635        label: &str,
1636        texture_view: &wgpu::TextureView,
1637    ) -> wgpu::BindGroup {
1638        let resources = self.resources();
1639        resources
1640            .device
1641            .create_bind_group(&wgpu::BindGroupDescriptor {
1642                label: Some(label),
1643                layout: &resources.bind_group_layouts.texture,
1644                entries: &[
1645                    wgpu::BindGroupEntry {
1646                        binding: 0,
1647                        resource: wgpu::BindingResource::TextureView(texture_view),
1648                    },
1649                    wgpu::BindGroupEntry {
1650                        binding: 1,
1651                        resource: wgpu::BindingResource::Sampler(&resources.atlas_sampler),
1652                    },
1653                ],
1654            })
1655    }
1656
1657    fn prepare_texture_bind_groups(&mut self, scene: &Scene) {
1658        let mut texture_ids = SmallVec::<[AtlasTextureId; 8]>::new();
1659        for batch in scene.batches() {
1660            let texture_id = match batch {
1661                PrimitiveBatch::MonochromeSprites { texture_id, .. }
1662                | PrimitiveBatch::SubpixelSprites { texture_id, .. }
1663                | PrimitiveBatch::PolychromeSprites { texture_id, .. } => texture_id,
1664                _ => continue,
1665            };
1666            if !texture_ids.contains(&texture_id) {
1667                texture_ids.push(texture_id);
1668            }
1669        }
1670
1671        self.resources_mut()
1672            .atlas_texture_bind_groups
1673            .retain(|texture_id, _| texture_ids.contains(texture_id));
1674
1675        for texture_id in texture_ids {
1676            let Some(texture_info) = self.atlas.get_texture_info(texture_id) else {
1677                self.resources_mut()
1678                    .atlas_texture_bind_groups
1679                    .remove(&texture_id);
1680                continue;
1681            };
1682            let is_current = self
1683                .resources()
1684                .atlas_texture_bind_groups
1685                .get(&texture_id)
1686                .is_some_and(|cached| cached.texture_generation == texture_info.generation);
1687            if is_current {
1688                continue;
1689            }
1690
1691            let bind_group =
1692                self.create_texture_bind_group("atlas_texture_bind_group", &texture_info.view);
1693            self.resources_mut().atlas_texture_bind_groups.insert(
1694                texture_id,
1695                CachedTextureBindGroup {
1696                    texture_generation: texture_info.generation,
1697                    bind_group,
1698                },
1699            );
1700        }
1701    }
1702
1703    fn draw_instances(
1704        &self,
1705        instances: &InstanceBinding,
1706        pipeline: &wgpu::RenderPipeline,
1707        range: Range<u32>,
1708        pass: &mut wgpu::RenderPass<'_>,
1709    ) {
1710        if range.is_empty() {
1711            return;
1712        }
1713        pass.set_pipeline(pipeline);
1714        pass.set_bind_group(1, &instances.bind_group, &[]);
1715        pass.draw(
1716            0..4,
1717            instances.first_instance + range.start..instances.first_instance + range.end,
1718        );
1719    }
1720
1721    fn draw_sprites(
1722        &self,
1723        sprite_instances: &InstanceBinding,
1724        texture_id: AtlasTextureId,
1725        pipeline: &wgpu::RenderPipeline,
1726        range: Range<u32>,
1727        pass: &mut wgpu::RenderPass<'_>,
1728    ) -> Result<()> {
1729        if range.is_empty() {
1730            return Ok(());
1731        }
1732        let resources = self.resources();
1733        // The atlas has released this texture; the batch belongs to a stale
1734        // paint that will be replaced once its view re-renders.
1735        let Some(texture) = resources.atlas_texture_bind_groups.get(&texture_id) else {
1736            return Ok(());
1737        };
1738        pass.set_pipeline(pipeline);
1739        pass.set_bind_group(1, &sprite_instances.bind_group, &[]);
1740        pass.set_bind_group(2, &texture.bind_group, &[]);
1741        pass.draw(
1742            0..4,
1743            sprite_instances.first_instance + range.start
1744                ..sprite_instances.first_instance + range.end,
1745        );
1746        Ok(())
1747    }
1748
1749    unsafe fn instance_bytes<T>(instances: &[T]) -> &[u8] {
1750        unsafe {
1751            std::slice::from_raw_parts(
1752                instances.as_ptr() as *const u8,
1753                std::mem::size_of_val(instances),
1754            )
1755        }
1756    }
1757
1758    /// The alignment of an allocation of `byte_len` bytes of `stride`-sized
1759    /// records, and the bytes it takes up from that aligned offset.
1760    fn instance_allocation_layout(&self, stride: u64, byte_len: u64) -> (u64, u64) {
1761        // wgpu rejects zero-sized bindings, so empty primitive arrays still
1762        // reserve the 16-byte minimum.
1763        let size = byte_len.max(16);
1764        if self.uses_webgl_instance_data {
1765            // The texture transport has no binding offset: the shader indexes
1766            // the instance texture absolutely, so each allocation must start on
1767            // a whole instance (a stride multiple) and a whole texel, and must
1768            // end on a texel boundary so the zero padding of its final partial
1769            // texel cannot overlap the next allocation.
1770            (
1771                least_common_multiple(self.instance_data_alignment, stride),
1772                size.next_multiple_of(INSTANCE_TEXTURE_TEXEL_SIZE),
1773            )
1774        } else {
1775            (self.instance_data_alignment.max(1), size)
1776        }
1777    }
1778
1779    /// The most space `instances` can take up, including alignment padding.
1780    fn instance_allocation_bound<T>(&self, instances: &[T]) -> u64 {
1781        let stride = (std::mem::size_of::<T>() as u64).max(1);
1782        let (alignment, allocation_size) =
1783            self.instance_allocation_layout(stride, std::mem::size_of_val(instances) as u64);
1784        alignment + allocation_size
1785    }
1786
1787    /// Grows the instance data up front if `size` more bytes won't fit, so the
1788    /// allocations that follow land in the same buffer or texture.
1789    fn reserve_instance_data(&mut self, instance_offset: &mut u64, size: u64) -> Result<()> {
1790        if *instance_offset + size > self.instance_data_capacity {
1791            self.grow_instance_data(size)?;
1792            *instance_offset = 0;
1793        }
1794        Ok(())
1795    }
1796
1797    fn write_instance_data<T>(
1798        &mut self,
1799        instance_offset: &mut u64,
1800        instances: &[T],
1801    ) -> Result<InstanceAllocation> {
1802        let data = unsafe { Self::instance_bytes(instances) };
1803        let stride = (std::mem::size_of::<T>() as u64).max(1);
1804        let (alignment, allocation_size) =
1805            self.instance_allocation_layout(stride, data.len() as u64);
1806        let mut offset = (*instance_offset).next_multiple_of(alignment);
1807        if offset + allocation_size > self.instance_data_capacity {
1808            self.grow_instance_data(allocation_size)?;
1809            offset = 0;
1810        }
1811        *instance_offset = offset + allocation_size;
1812
1813        let first_instance = if self.uses_webgl_instance_data {
1814            u32::try_from(offset / stride).context("instance index exceeds u32 range")?
1815        } else {
1816            0
1817        };
1818
1819        let resources = self.resources();
1820        if !data.is_empty() {
1821            match &resources.instance_data {
1822                InstanceData::Storage(buffer) => resources.queue.write_buffer(buffer, offset, data),
1823                InstanceData::Texture { .. } => {
1824                    Self::write_instance_texture(resources, offset, data)
1825                }
1826            }
1827        }
1828        Ok(InstanceAllocation {
1829            offset,
1830            size: (data.len() as u64).max(16),
1831            first_instance,
1832        })
1833    }
1834
1835    fn instance_binding_resource(
1836        &self,
1837        allocation: &InstanceAllocation,
1838    ) -> wgpu::BindingResource<'_> {
1839        match &self.resources().instance_data {
1840            InstanceData::Storage(buffer) => wgpu::BindingResource::Buffer(wgpu::BufferBinding {
1841                buffer,
1842                offset: allocation.offset,
1843                size: NonZeroU64::new(allocation.size),
1844            }),
1845            InstanceData::Texture { view, .. } => wgpu::BindingResource::TextureView(view),
1846        }
1847    }
1848
1849    fn write_instance_binding<T>(
1850        &mut self,
1851        label: &str,
1852        instance_offset: &mut u64,
1853        instances: &[T],
1854    ) -> Result<InstanceBinding> {
1855        let allocation = self.write_instance_data(instance_offset, instances)?;
1856        let resources = self.resources();
1857        let bind_group = resources
1858            .device
1859            .create_bind_group(&wgpu::BindGroupDescriptor {
1860                label: Some(label),
1861                layout: &resources.bind_group_layouts.instances,
1862                entries: &[wgpu::BindGroupEntry {
1863                    binding: 0,
1864                    resource: self.instance_binding_resource(&allocation),
1865                }],
1866            });
1867        Ok(InstanceBinding {
1868            bind_group,
1869            first_instance: allocation.first_instance,
1870        })
1871    }
1872
1873    fn write_path_tiles(
1874        &mut self,
1875        scene: &Scene,
1876        instance_offset: &mut u64,
1877    ) -> Result<PathTileBinding> {
1878        let mut paint_data = Vec::with_capacity(scene.paths.len());
1879        let mut curve_data = Vec::new();
1880        let mut tile_data = Vec::new();
1881        for path in &scene.paths {
1882            path.append_to(&mut paint_data, &mut curve_data, &mut tile_data);
1883        }
1884
1885        // All three arrays are bound together, so they must not be split by a
1886        // grow partway through.
1887        let reserved = self.instance_allocation_bound(&paint_data)
1888            + self.instance_allocation_bound(&curve_data)
1889            + self.instance_allocation_bound(&tile_data);
1890        self.reserve_instance_data(instance_offset, reserved)?;
1891
1892        let paints = self.write_instance_data(instance_offset, &paint_data)?;
1893        let curves = self.write_instance_data(instance_offset, &curve_data)?;
1894        let tiles = self.write_instance_data(instance_offset, &tile_data)?;
1895
1896        let resources = self.resources();
1897        let bind_group = if self.uses_webgl_instance_data {
1898            resources
1899                .device
1900                .create_bind_group(&wgpu::BindGroupDescriptor {
1901                    label: Some("path_tiles_bind_group"),
1902                    layout: &resources.bind_group_layouts.path_tiles,
1903                    entries: &[wgpu::BindGroupEntry {
1904                        binding: 0,
1905                        resource: self.instance_binding_resource(&tiles),
1906                    }],
1907                })
1908        } else {
1909            resources
1910                .device
1911                .create_bind_group(&wgpu::BindGroupDescriptor {
1912                    label: Some("path_tiles_bind_group"),
1913                    layout: &resources.bind_group_layouts.path_tiles,
1914                    entries: &[
1915                        wgpu::BindGroupEntry {
1916                            binding: 0,
1917                            resource: self.instance_binding_resource(&tiles),
1918                        },
1919                        wgpu::BindGroupEntry {
1920                            binding: 1,
1921                            resource: self.instance_binding_resource(&curves),
1922                        },
1923                        wgpu::BindGroupEntry {
1924                            binding: 2,
1925                            resource: self.instance_binding_resource(&paints),
1926                        },
1927                    ],
1928                })
1929        };
1930        Ok(PathTileBinding {
1931            tiles: InstanceBinding {
1932                bind_group,
1933                first_instance: tiles.first_instance,
1934            },
1935            paint_base: paints.first_instance,
1936            curve_base: curves.first_instance,
1937        })
1938    }
1939
1940    fn write_instance_texture(resources: &WgpuResources, offset: u64, data: &[u8]) {
1941        let InstanceData::Texture {
1942            texture,
1943            width,
1944            height,
1945            ..
1946        } = &resources.instance_data
1947        else {
1948            return;
1949        };
1950        let mut byte_offset = 0usize;
1951        let mut texel_offset = offset / INSTANCE_TEXTURE_TEXEL_SIZE;
1952        while byte_offset < data.len() {
1953            let x = (texel_offset % u64::from(*width)) as u32;
1954            let y = (texel_offset / u64::from(*width)) as u32;
1955            if y >= *height {
1956                // The capacity check in write_instance_binding should make this
1957                // unreachable. Truncating silently would leave stale bytes in the
1958                // texture and draw garbage for the remaining instances.
1959                debug_assert!(
1960                    false,
1961                    "instance texture write out of bounds: row {y} >= height {}",
1962                    *height
1963                );
1964                log::error!(
1965                    "instance texture write out of bounds; dropping {} bytes of instance data",
1966                    data.len() - byte_offset
1967                );
1968                return;
1969            }
1970            let available_texels = u64::from(*width - x);
1971            let remaining_bytes = data.len() - byte_offset;
1972            let complete_texels = remaining_bytes as u64 / INSTANCE_TEXTURE_TEXEL_SIZE;
1973            let texels = complete_texels.min(available_texels);
1974            if texels > 0 {
1975                let byte_count = (texels * INSTANCE_TEXTURE_TEXEL_SIZE) as usize;
1976                resources.queue.write_texture(
1977                    wgpu::TexelCopyTextureInfo {
1978                        texture,
1979                        mip_level: 0,
1980                        origin: wgpu::Origin3d { x, y, z: 0 },
1981                        aspect: wgpu::TextureAspect::All,
1982                    },
1983                    &data[byte_offset..byte_offset + byte_count],
1984                    wgpu::TexelCopyBufferLayout {
1985                        offset: 0,
1986                        bytes_per_row: Some(byte_count as u32),
1987                        rows_per_image: None,
1988                    },
1989                    wgpu::Extent3d {
1990                        width: texels as u32,
1991                        height: 1,
1992                        depth_or_array_layers: 1,
1993                    },
1994                );
1995                byte_offset += byte_count;
1996                texel_offset += texels;
1997                continue;
1998            }
1999
2000            let mut final_texel = [0; INSTANCE_TEXTURE_TEXEL_SIZE as usize];
2001            final_texel[..remaining_bytes].copy_from_slice(&data[byte_offset..]);
2002            resources.queue.write_texture(
2003                wgpu::TexelCopyTextureInfo {
2004                    texture,
2005                    mip_level: 0,
2006                    origin: wgpu::Origin3d { x, y, z: 0 },
2007                    aspect: wgpu::TextureAspect::All,
2008                },
2009                &final_texel,
2010                wgpu::TexelCopyBufferLayout {
2011                    offset: 0,
2012                    bytes_per_row: Some(INSTANCE_TEXTURE_TEXEL_SIZE as u32),
2013                    rows_per_image: None,
2014                },
2015                wgpu::Extent3d {
2016                    width: 1,
2017                    height: 1,
2018                    depth_or_array_layers: 1,
2019                },
2020            );
2021            break;
2022        }
2023    }
2024
2025    fn grow_instance_data(&mut self, required: u64) -> Result<()> {
2026        let capacity = (self.instance_data_capacity * 2)
2027            .max(required.next_power_of_two())
2028            .min(self.max_instance_data_size);
2029        anyhow::ensure!(
2030            capacity >= required,
2031            "instance data needs {required} bytes, above the maximum of {}",
2032            self.max_instance_data_size
2033        );
2034        anyhow::ensure!(
2035            capacity > self.instance_data_capacity,
2036            "frame instance data exceeds the {}-byte maximum",
2037            self.max_instance_data_size
2038        );
2039        log::debug!(
2040            "instance data grown from {} to {capacity}",
2041            self.instance_data_capacity
2042        );
2043        // Bind groups created earlier in the frame keep the previous buffer or
2044        // texture alive, so allocations written before the grow remain valid;
2045        // only subsequent writes land in the new allocation.
2046        let uses_webgl_instance_data = self.uses_webgl_instance_data;
2047        let resources = self.resources_mut();
2048        if uses_webgl_instance_data {
2049            let max_texture_dimension = resources.device.limits().max_texture_dimension_2d;
2050            let (instance_data, actual_capacity) =
2051                Self::create_instance_texture(&resources.device, capacity, max_texture_dimension);
2052            resources.instance_data = instance_data;
2053            self.instance_data_capacity = actual_capacity;
2054        } else {
2055            resources.instance_data =
2056                InstanceData::Storage(resources.device.create_buffer(&wgpu::BufferDescriptor {
2057                    label: Some("instance_buffer"),
2058                    size: capacity,
2059                    usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
2060                    mapped_at_creation: false,
2061                }));
2062            self.instance_data_capacity = capacity;
2063        }
2064        Ok(())
2065    }
2066}
2067
2068impl WgpuRenderer {
2069    /// Mark the surface as unconfigured so rendering is skipped until a new
2070    /// surface is provided via [`replace_surface`](Self::replace_surface).
2071    ///
2072    /// This does **not** drop the renderer — the device, queue, atlas, and
2073    /// pipelines stay alive.  Use this when the native window is destroyed
2074    /// (e.g. Android `TerminateWindow`) but you intend to re-create the
2075    /// surface later without losing cached atlas textures.
2076    pub fn unconfigure_surface(&mut self) {
2077        self.state = match std::mem::replace(&mut self.state, RendererState::Released) {
2078            RendererState::Ready { core, surface } => {
2079                drop(surface);
2080                RendererState::Unconfigured { core }
2081            }
2082            state @ (RendererState::Unconfigured { .. } | RendererState::Released) => state,
2083        };
2084    }
2085
2086    /// Replace the wgpu surface with a new one (e.g. after Android destroys
2087    /// and recreates the native window).  Keeps the device, queue, atlas, and
2088    /// all pipelines intact so cached `AtlasTextureId`s remain valid.
2089    ///
2090    /// The `instance` **must** be the same [`wgpu::Instance`] that was used to
2091    /// create the adapter and device (i.e. from the [`WgpuContext`]).  Using a
2092    /// different instance will cause a "Device does not exist" panic because
2093    /// the wgpu device is bound to its originating instance.
2094    #[cfg(not(target_family = "wasm"))]
2095    pub fn replace_surface<W: HasWindowHandle>(
2096        &mut self,
2097        window: &W,
2098        config: WgpuSurfaceConfig,
2099        instance: &wgpu::Instance,
2100    ) -> anyhow::Result<()> {
2101        let window_handle = window
2102            .window_handle()
2103            .map_err(|e| anyhow::anyhow!("Failed to get window handle: {e}"))?;
2104
2105        let surface = create_surface(instance, window_handle.as_raw())?;
2106
2107        let width = (config.size.width.0 as u32).max(1);
2108        let height = (config.size.height.0 as u32).max(1);
2109
2110        let alpha_mode = if config.transparent {
2111            self.transparent_alpha_mode
2112        } else {
2113            self.opaque_alpha_mode
2114        };
2115        let alpha_mode_changed = alpha_mode != self.surface_config.alpha_mode;
2116
2117        self.surface_config.width = width;
2118        self.surface_config.height = height;
2119        self.surface_config.alpha_mode = alpha_mode;
2120        if let Some(mode) = config.preferred_present_mode {
2121            self.surface_config.present_mode = mode;
2122        }
2123
2124        let mut core = match std::mem::replace(&mut self.state, RendererState::Released) {
2125            RendererState::Ready {
2126                core,
2127                surface: old_surface,
2128            } => {
2129                drop(old_surface);
2130                core
2131            }
2132            RendererState::Unconfigured { core } => core,
2133            RendererState::Released => {
2134                anyhow::bail!("Cannot replace the surface: GPU resources have been released")
2135            }
2136        };
2137        if alpha_mode_changed {
2138            core.rebuild_pipelines(self.surface_config.format, alpha_mode);
2139        }
2140        surface.configure(&core.resources.device, &self.surface_config);
2141        self.state = RendererState::Ready { surface, core };
2142
2143        Ok(())
2144    }
2145
2146    pub fn destroy(&mut self) {
2147        // Release surface-bound GPU resources eagerly so the underlying native
2148        // window can be destroyed before the renderer itself is dropped.
2149        self.state = RendererState::Released;
2150    }
2151
2152    /// Returns true if the GPU device was lost and recovery is needed.
2153    pub fn device_lost(&self) -> bool {
2154        self.device_errors.device_lost()
2155    }
2156
2157    /// Returns true if a redraw is needed because GPU state was cleared.
2158    /// Calling this method clears the flag.
2159    pub fn needs_redraw(&mut self) -> bool {
2160        std::mem::take(&mut self.needs_redraw)
2161    }
2162
2163    /// Recovers from a lost GPU device by recreating the renderer with a new context.
2164    ///
2165    /// Call this after detecting `device_lost()` returns true.
2166    ///
2167    /// This method coordinates recovery across multiple windows:
2168    /// - The first window to call this will recreate the shared context
2169    /// - Subsequent windows will adopt the already-recovered context
2170    #[cfg(not(target_family = "wasm"))]
2171    pub fn recover<W>(&mut self, window: &W) -> anyhow::Result<()>
2172    where
2173        W: HasWindowHandle + HasDisplayHandle + std::fmt::Debug + Send + Sync + Clone + 'static,
2174    {
2175        let gpu_context = self.context.as_ref().expect("recover requires gpu_context");
2176
2177        // Check if another window already recovered the context
2178        let needs_new_context = gpu_context
2179            .borrow()
2180            .as_ref()
2181            .is_none_or(|ctx| ctx.device_lost());
2182
2183        let window_handle = window
2184            .window_handle()
2185            .map_err(|e| anyhow::anyhow!("Failed to get window handle: {e}"))?;
2186
2187        let config = WgpuSurfaceConfig {
2188            size: gpui::Size {
2189                width: gpui::DevicePixels(self.surface_config.width as i32),
2190                height: gpui::DevicePixels(self.surface_config.height as i32),
2191            },
2192            transparent: self.surface_config.alpha_mode != wgpu::CompositeAlphaMode::Opaque,
2193            preferred_present_mode: Some(self.surface_config.present_mode),
2194        };
2195
2196        let surface = if needs_new_context {
2197            log::warn!("GPU device lost, recreating context...");
2198
2199            // Drop old resources to release Arc<Device>/Arc<Queue> and GPU resources
2200            self.state = RendererState::Released;
2201            *gpu_context.borrow_mut() = None;
2202
2203            // Wait briefly for the GPU driver to stabilize, then try to
2204            // recreate the context without software renderers. If this fails
2205            // the caller should request another frame and retry — the real GPU
2206            // may need more time to come back (e.g. after suspend/resume).
2207            std::thread::sleep(std::time::Duration::from_millis(350));
2208
2209            let instance = WgpuContext::instance(Some(Box::new(window.clone())));
2210            let surface = create_surface(&instance, window_handle.as_raw())?;
2211            let new_context = WgpuContext::new_rejecting_software(
2212                instance,
2213                &surface,
2214                &config,
2215                self.compositor_gpu,
2216            )?;
2217            *gpu_context.borrow_mut() = Some(new_context);
2218            surface
2219        } else {
2220            let ctx_ref = gpu_context.borrow();
2221            let instance = &ctx_ref.as_ref().unwrap().instance;
2222            create_surface(instance, window_handle.as_raw())?
2223        };
2224
2225        let gpu_context = Rc::clone(gpu_context);
2226        let ctx_ref = gpu_context.borrow();
2227        let context = ctx_ref.as_ref().expect("context should exist");
2228
2229        self.state = RendererState::Released;
2230        self.atlas.handle_device_lost(context);
2231
2232        let is_bgr = self.is_bgr;
2233        *self = Self::new_internal(
2234            Some(gpu_context.clone()),
2235            context,
2236            surface,
2237            config,
2238            needs_new_context,
2239            self.compositor_gpu,
2240            self.atlas.clone(),
2241        )?;
2242        self.set_subpixel_layout(is_bgr);
2243
2244        log::info!("GPU recovery complete");
2245        Ok(())
2246    }
2247}
2248
2249#[cfg(all(
2250    not(target_family = "wasm"),
2251    any(test, feature = "bench-support", feature = "test-support")
2252))]
2253struct HeadlessRenderTarget {
2254    texture: wgpu::Texture,
2255    view: wgpu::TextureView,
2256}
2257
2258#[cfg(all(
2259    not(target_family = "wasm"),
2260    any(test, feature = "bench-support", feature = "test-support")
2261))]
2262impl HeadlessRenderTarget {
2263    fn size(&self) -> Size<DevicePixels> {
2264        Size {
2265            width: DevicePixels(self.texture.width() as i32),
2266            height: DevicePixels(self.texture.height() as i32),
2267        }
2268    }
2269}
2270
2271#[cfg(all(
2272    not(target_family = "wasm"),
2273    any(test, feature = "bench-support", feature = "test-support")
2274))]
2275pub struct WgpuHeadlessRenderer {
2276    context: WgpuContext,
2277    core: WgpuRendererCore,
2278    render_target: Option<HeadlessRenderTarget>,
2279    observed_error_generation: u64,
2280}
2281
2282#[cfg(all(
2283    not(target_family = "wasm"),
2284    any(test, feature = "bench-support", feature = "test-support")
2285))]
2286impl WgpuHeadlessRenderer {
2287    pub fn new() -> anyhow::Result<Self> {
2288        let (context, target_format) = WgpuContext::new_headless()?;
2289        // The device may be shared with earlier renderers; observe only errors raised from
2290        // here on, including any while this renderer builds its pipelines.
2291        let observed_error_generation = context.errors().current_generation();
2292        let atlas = Arc::new(WgpuAtlas::from_context(&context));
2293        let core = WgpuRendererCore::new(
2294            &context,
2295            atlas,
2296            target_format,
2297            wgpu::CompositeAlphaMode::Opaque,
2298        );
2299
2300        Ok(Self {
2301            context,
2302            core,
2303            render_target: None,
2304            observed_error_generation,
2305        })
2306    }
2307
2308    fn ensure_render_target(&mut self, size: Size<DevicePixels>) -> anyhow::Result<()> {
2309        anyhow::ensure!(
2310            size.width.0 > 0 && size.height.0 > 0,
2311            "invalid headless render target size: {size:?}"
2312        );
2313        anyhow::ensure!(
2314            size.width.0 as u32 <= self.core.max_texture_size
2315                && size.height.0 as u32 <= self.core.max_texture_size,
2316            "headless render target size {size:?} exceeds maximum texture dimension {}",
2317            self.core.max_texture_size
2318        );
2319        if self
2320            .render_target
2321            .as_ref()
2322            .is_some_and(|target| target.size() == size)
2323        {
2324            return Ok(());
2325        }
2326
2327        let texture = self
2328            .core
2329            .resources
2330            .device
2331            .create_texture(&wgpu::TextureDescriptor {
2332                label: Some("headless_render_target"),
2333                size: wgpu::Extent3d {
2334                    width: size.width.0 as u32,
2335                    height: size.height.0 as u32,
2336                    depth_or_array_layers: 1,
2337                },
2338                mip_level_count: 1,
2339                sample_count: 1,
2340                dimension: wgpu::TextureDimension::D2,
2341                format: self.core.target_format,
2342                usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
2343                view_formats: &[],
2344            });
2345        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
2346        self.render_target = Some(HeadlessRenderTarget { texture, view });
2347        Ok(())
2348    }
2349
2350    fn check_gpu_errors(&mut self) -> anyhow::Result<()> {
2351        anyhow::ensure!(
2352            !self.context.device_lost(),
2353            "GPU device was lost during headless rendering"
2354        );
2355        if let Some(error) = self
2356            .context
2357            .errors()
2358            .observe_error(&mut self.observed_error_generation)
2359        {
2360            anyhow::bail!("GPU error during headless rendering: {error}");
2361        }
2362        Ok(())
2363    }
2364
2365    fn render(&mut self, scene: &Scene, size: Size<DevicePixels>) -> anyhow::Result<()> {
2366        self.check_gpu_errors()?;
2367        self.ensure_render_target(size)?;
2368        let view = self
2369            .render_target
2370            .as_ref()
2371            .ok_or_else(|| anyhow::anyhow!("Headless render target was not created"))?
2372            .view
2373            .clone();
2374        self.core
2375            .render_frame(scene, &view, size, wgpu::Color::BLACK)?;
2376        Ok(())
2377    }
2378
2379    /// Copies the current render target back to the CPU. Dimensions come from the
2380    /// target texture itself, so the copy can never disagree with what was rendered.
2381    fn read_image(&mut self) -> anyhow::Result<image::RgbaImage> {
2382        let target = self
2383            .render_target
2384            .as_ref()
2385            .ok_or_else(|| anyhow::anyhow!("Headless render target was not created"))?;
2386        let width = target.texture.width();
2387        let height = target.texture.height();
2388        let bytes_per_row = width
2389            .checked_mul(4)
2390            .ok_or_else(|| anyhow::anyhow!("Headless render target row size overflowed"))?;
2391        let padded_bytes_per_row = bytes_per_row
2392            .checked_next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
2393            .ok_or_else(|| anyhow::anyhow!("Headless padded row size overflowed"))?;
2394        let buffer_size = u64::from(padded_bytes_per_row)
2395            .checked_mul(u64::from(height))
2396            .ok_or_else(|| anyhow::anyhow!("Headless readback buffer size overflowed"))?;
2397        anyhow::ensure!(
2398            buffer_size <= self.core.resources.device.limits().max_buffer_size,
2399            "Headless readback buffer size {buffer_size} exceeds maximum buffer size {}",
2400            self.core.resources.device.limits().max_buffer_size
2401        );
2402        let readback_buffer = self
2403            .core
2404            .resources
2405            .device
2406            .create_buffer(&wgpu::BufferDescriptor {
2407                label: Some("headless_readback_buffer"),
2408                size: buffer_size,
2409                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
2410                mapped_at_creation: false,
2411            });
2412        let mut encoder =
2413            self.core
2414                .resources
2415                .device
2416                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
2417                    label: Some("headless_readback_encoder"),
2418                });
2419        encoder.copy_texture_to_buffer(
2420            wgpu::TexelCopyTextureInfo {
2421                texture: &target.texture,
2422                mip_level: 0,
2423                origin: wgpu::Origin3d::ZERO,
2424                aspect: wgpu::TextureAspect::All,
2425            },
2426            wgpu::TexelCopyBufferInfo {
2427                buffer: &readback_buffer,
2428                layout: wgpu::TexelCopyBufferLayout {
2429                    offset: 0,
2430                    bytes_per_row: Some(padded_bytes_per_row),
2431                    rows_per_image: Some(height),
2432                },
2433            },
2434            wgpu::Extent3d {
2435                width,
2436                height,
2437                depth_or_array_layers: 1,
2438            },
2439        );
2440        let submission = self
2441            .core
2442            .resources
2443            .queue
2444            .submit(std::iter::once(encoder.finish()));
2445        let (sender, receiver) = std::sync::mpsc::channel();
2446        readback_buffer
2447            .slice(..)
2448            .map_async(wgpu::MapMode::Read, move |result| {
2449                if sender.send(result).is_err() {
2450                    log::error!("Headless readback receiver was dropped before mapping completed");
2451                }
2452            });
2453        self.core
2454            .resources
2455            .device
2456            .poll(wgpu::PollType::Wait {
2457                submission_index: Some(submission),
2458                timeout: Some(std::time::Duration::from_secs(30)),
2459            })
2460            .map_err(|error| anyhow::anyhow!("Failed to wait for headless rendering: {error}"))?;
2461        receiver
2462            .recv_timeout(std::time::Duration::from_secs(30))
2463            .map_err(|error| anyhow::anyhow!("Failed to receive headless mapping result: {error}"))?
2464            .map_err(|error| anyhow::anyhow!("Failed to map headless readback buffer: {error}"))?;
2465        self.check_gpu_errors()?;
2466
2467        let mapped_data = readback_buffer.slice(..).get_mapped_range()?;
2468        let pixel_capacity = usize::try_from(u64::from(bytes_per_row) * u64::from(height))
2469            .map_err(|_| anyhow::anyhow!("Headless image size exceeds addressable memory"))?;
2470        let mut pixels = Vec::with_capacity(pixel_capacity);
2471        for row in mapped_data
2472            .chunks_exact(padded_bytes_per_row as usize)
2473            .take(height as usize)
2474        {
2475            pixels.extend_from_slice(&row[..bytes_per_row as usize]);
2476        }
2477        drop(mapped_data);
2478        readback_buffer.unmap();
2479
2480        if self.core.target_format == wgpu::TextureFormat::Bgra8Unorm {
2481            for pixel in pixels.chunks_exact_mut(4) {
2482                pixel.swap(0, 2);
2483            }
2484        }
2485
2486        image::RgbaImage::from_raw(width, height, pixels)
2487            .ok_or_else(|| anyhow::anyhow!("Failed to create image from headless pixel data"))
2488    }
2489}
2490
2491#[cfg(all(
2492    not(target_family = "wasm"),
2493    any(test, feature = "bench-support", feature = "test-support")
2494))]
2495impl gpui::PlatformHeadlessRenderer for WgpuHeadlessRenderer {
2496    fn render_scene_to_image(
2497        &mut self,
2498        scene: &Scene,
2499        size: Size<DevicePixels>,
2500    ) -> anyhow::Result<image::RgbaImage> {
2501        self.render(scene, size)?;
2502        self.read_image()
2503    }
2504
2505    fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> anyhow::Result<()> {
2506        self.render(scene, size)
2507    }
2508
2509    fn sprite_atlas(&self) -> Arc<dyn gpui::PlatformAtlas> {
2510        self.core.atlas.clone()
2511    }
2512}
2513
2514fn instance_range(range: Range<usize>) -> Range<u32> {
2515    range.start as u32..range.end as u32
2516}
2517
2518#[cfg(not(target_family = "wasm"))]
2519fn create_surface(
2520    instance: &wgpu::Instance,
2521    raw_window_handle: raw_window_handle::RawWindowHandle,
2522) -> anyhow::Result<wgpu::Surface<'static>> {
2523    unsafe {
2524        instance
2525            .create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle {
2526                // Fall back to the display handle already provided via InstanceDescriptor::display.
2527                raw_display_handle: None,
2528                raw_window_handle,
2529            })
2530            .map_err(|e| anyhow::anyhow!("{e}"))
2531    }
2532}
2533
2534struct RenderingParameters {
2535    gamma_ratios: [f32; 4],
2536    grayscale_enhanced_contrast: f32,
2537    subpixel_enhanced_contrast: f32,
2538}
2539
2540impl RenderingParameters {
2541    fn new() -> Self {
2542        use std::env;
2543
2544        let gamma = env::var("ZED_FONTS_GAMMA")
2545            .ok()
2546            .and_then(|v| v.parse().ok())
2547            .unwrap_or(1.8_f32)
2548            .clamp(1.0, 2.2);
2549        let gamma_ratios = get_gamma_correction_ratios(gamma);
2550
2551        let grayscale_enhanced_contrast = env::var("ZED_FONTS_GRAYSCALE_ENHANCED_CONTRAST")
2552            .ok()
2553            .and_then(|v| v.parse().ok())
2554            .unwrap_or(1.0_f32)
2555            .max(0.0);
2556
2557        let subpixel_enhanced_contrast = env::var("ZED_FONTS_SUBPIXEL_ENHANCED_CONTRAST")
2558            .ok()
2559            .and_then(|v| v.parse().ok())
2560            .unwrap_or(0.5_f32)
2561            .max(0.0);
2562
2563        Self {
2564            gamma_ratios,
2565            grayscale_enhanced_contrast,
2566            subpixel_enhanced_contrast,
2567        }
2568    }
2569}
2570
2571#[cfg(test)]
2572mod tests {
2573    use super::*;
2574    use gpui::{
2575        BorderStyle, ColorSpace, ContentMask, Corners, Edges, Hsla, MonochromeSprite, PathCurve,
2576        PathPaint, PathTile, Point, PolychromeSprite, Quad, Shadow, Size, SubpixelSprite,
2577        Underline, linear_color_stop, linear_gradient,
2578    };
2579    #[cfg(target_os = "linux")]
2580    use gpui::{DevicePixels, PlatformHeadlessRenderer, Scene};
2581
2582    #[cfg(target_os = "linux")]
2583    fn device_size(width: i32, height: i32) -> Size<DevicePixels> {
2584        Size {
2585            width: DevicePixels(width),
2586            height: DevicePixels(height),
2587        }
2588    }
2589
2590    #[cfg(target_os = "linux")]
2591    fn solid_quad(x: f32, y: f32, width: f32, height: f32, color: Hsla) -> Quad {
2592        let bounds = Bounds {
2593            origin: Point {
2594                x: x.into(),
2595                y: y.into(),
2596            },
2597            size: Size {
2598                width: width.into(),
2599                height: height.into(),
2600            },
2601        };
2602        Quad {
2603            order: 0,
2604            border_style: BorderStyle::Solid,
2605            bounds,
2606            content_mask: ContentMask { bounds },
2607            background: color.into(),
2608            border_color: color,
2609            corner_radii: Corners::default(),
2610            border_widths: Edges::default(),
2611        }
2612    }
2613
2614    /// Channels are compared with a small tolerance so the assertions hold across
2615    /// drivers without pinning exact rasterizer output.
2616    #[cfg(target_os = "linux")]
2617    fn assert_pixel(image: &image::RgbaImage, x: u32, y: u32, expected: [u8; 4]) {
2618        let actual = image.get_pixel(x, y).0;
2619        assert!(
2620            actual
2621                .iter()
2622                .zip(expected)
2623                .all(|(actual, expected)| actual.abs_diff(expected) <= 3),
2624            "pixel ({x}, {y}) was {actual:?}, expected {expected:?}"
2625        );
2626    }
2627
2628    #[cfg(target_os = "linux")]
2629    const RED: [u8; 4] = [255, 0, 0, 255];
2630    #[cfg(target_os = "linux")]
2631    const BLUE: [u8; 4] = [0, 0, 255, 255];
2632    #[cfg(target_os = "linux")]
2633    const BLACK: [u8; 4] = [0, 0, 0, 255];
2634
2635    #[cfg(target_os = "linux")]
2636    #[test]
2637    fn headless_renderer_draws_quads_with_distinct_colors() -> anyhow::Result<()> {
2638        let mut renderer = WgpuHeadlessRenderer::new()?;
2639        let mut scene = Scene::default();
2640        scene.insert_primitive(solid_quad(0.0, 0.0, 32.0, 32.0, gpui::red()));
2641        scene.insert_primitive(solid_quad(32.0, 0.0, 32.0, 32.0, gpui::blue()));
2642        scene.finish();
2643
2644        let image = renderer.render_scene_to_image(&scene, device_size(64, 32))?;
2645        assert_eq!(image.dimensions(), (64, 32));
2646        assert_pixel(&image, 8, 16, RED);
2647        assert_pixel(&image, 24, 16, RED);
2648        assert_pixel(&image, 40, 16, BLUE);
2649        assert_pixel(&image, 56, 16, BLUE);
2650        Ok(())
2651    }
2652
2653    #[cfg(target_os = "linux")]
2654    #[test]
2655    fn headless_renderer_captures_each_requested_size() -> anyhow::Result<()> {
2656        let mut renderer = WgpuHeadlessRenderer::new()?;
2657        let mut scene = Scene::default();
2658        scene.insert_primitive(solid_quad(2.0, 2.0, 4.0, 3.0, gpui::red()));
2659        scene.finish();
2660
2661        // 13 px rows are 52 bytes, forcing readback to strip copy-row padding.
2662        let image = renderer.render_scene_to_image(&scene, device_size(13, 7))?;
2663        assert_eq!(image.dimensions(), (13, 7));
2664        assert_pixel(&image, 0, 0, BLACK);
2665        assert_pixel(&image, 3, 3, RED);
2666        assert_pixel(&image, 12, 6, BLACK);
2667
2668        let image = renderer.render_scene_to_image(&scene, device_size(17, 9))?;
2669        assert_eq!(image.dimensions(), (17, 9));
2670        assert_pixel(&image, 3, 3, RED);
2671        assert_pixel(&image, 16, 8, BLACK);
2672
2673        let image = renderer.render_scene_to_image(&Scene::default(), device_size(13, 7))?;
2674        assert_eq!(image.dimensions(), (13, 7));
2675        assert!(image.pixels().all(|pixel| pixel.0 == BLACK));
2676        Ok(())
2677    }
2678
2679    #[cfg(target_os = "linux")]
2680    #[test]
2681    fn headless_renderer_reuses_target_for_same_size() -> anyhow::Result<()> {
2682        let mut renderer = WgpuHeadlessRenderer::new()?;
2683        let target_texture = |renderer: &WgpuHeadlessRenderer| {
2684            renderer
2685                .render_target
2686                .as_ref()
2687                .map(|target| target.texture.clone())
2688        };
2689
2690        renderer.render_scene(&Scene::default(), device_size(16, 16))?;
2691        let first = target_texture(&renderer);
2692        assert!(first.is_some());
2693
2694        renderer.render_scene(&Scene::default(), device_size(16, 16))?;
2695        assert_eq!(target_texture(&renderer), first);
2696
2697        renderer.render_scene(&Scene::default(), device_size(16, 17))?;
2698        assert_ne!(target_texture(&renderer), first);
2699        Ok(())
2700    }
2701
2702    #[cfg(target_os = "linux")]
2703    #[test]
2704    fn headless_renderer_rejects_invalid_sizes() -> anyhow::Result<()> {
2705        let mut renderer = WgpuHeadlessRenderer::new()?;
2706        let too_large = renderer.core.max_texture_size as i32 + 1;
2707
2708        for size in [
2709            device_size(0, 8),
2710            device_size(8, 0),
2711            device_size(-1, 8),
2712            device_size(too_large, 8),
2713        ] {
2714            assert!(
2715                renderer.render_scene(&Scene::default(), size).is_err(),
2716                "{size:?} should be rejected"
2717            );
2718            assert!(
2719                renderer
2720                    .render_scene_to_image(&Scene::default(), size)
2721                    .is_err(),
2722                "{size:?} should be rejected"
2723            );
2724        }
2725
2726        // Rejection must leave the renderer usable.
2727        let image = renderer.render_scene_to_image(&Scene::default(), device_size(4, 4))?;
2728        assert_eq!(image.dimensions(), (4, 4));
2729        Ok(())
2730    }
2731
2732    #[test]
2733    fn webgl_shader_is_valid_wgsl_without_storage_buffers() {
2734        assert!(!WEBGL_SHADERS.contains("var<storage"));
2735        validate_wgsl(WEBGL_SHADERS, naga::valid::Capabilities::empty());
2736    }
2737
2738    #[test]
2739    fn storage_buffer_shader_is_valid_wgsl() {
2740        validate_wgsl(STORAGE_BUFFER_SHADERS, naga::valid::Capabilities::empty());
2741    }
2742
2743    #[test]
2744    fn subpixel_shader_is_valid_wgsl() {
2745        validate_wgsl(
2746            SUBPIXEL_SHADERS,
2747            naga::valid::Capabilities::DUAL_SOURCE_BLENDING,
2748        );
2749    }
2750
2751    fn validate_wgsl(source: &str, capabilities: naga::valid::Capabilities) {
2752        let module = naga::front::wgsl::parse_str(source).expect("shader should parse");
2753        naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities)
2754            .validate(&module)
2755            .expect("shader should validate");
2756    }
2757
2758    #[test]
2759    fn webgl_record_sizes_match_shader_word_strides() {
2760        assert_eq!(std::mem::size_of::<Quad>(), 40 * 4);
2761        assert_eq!(std::mem::size_of::<Shadow>(), 28 * 4);
2762        assert_eq!(std::mem::size_of::<PathTile>(), 14 * 4);
2763        assert_eq!(std::mem::size_of::<PathCurve>(), 10 * 4);
2764        assert_eq!(std::mem::size_of::<PathPaint>(), 28 * 4);
2765        assert_eq!(std::mem::size_of::<Underline>(), 16 * 4);
2766        assert_eq!(std::mem::size_of::<MonochromeSprite>(), 28 * 4);
2767        assert_eq!(std::mem::size_of::<SubpixelSprite>(), 28 * 4);
2768        assert_eq!(std::mem::size_of::<PolychromeSprite>(), 24 * 4);
2769    }
2770
2771    #[test]
2772    fn webgl_quad_layout_matches_fixed_decoder() {
2773        let quad = Quad {
2774            order: 41,
2775            border_style: BorderStyle::Dashed,
2776            bounds: Bounds {
2777                origin: Point {
2778                    x: 1.0.into(),
2779                    y: 2.0.into(),
2780                },
2781                size: Size {
2782                    width: 3.0.into(),
2783                    height: 4.0.into(),
2784                },
2785            },
2786            content_mask: ContentMask {
2787                bounds: Bounds {
2788                    origin: Point {
2789                        x: 5.0.into(),
2790                        y: 6.0.into(),
2791                    },
2792                    size: Size {
2793                        width: 7.0.into(),
2794                        height: 8.0.into(),
2795                    },
2796                },
2797            },
2798            background: linear_gradient(
2799                11.0,
2800                linear_color_stop(
2801                    Hsla {
2802                        h: 12.0,
2803                        s: 13.0,
2804                        l: 14.0,
2805                        a: 15.0,
2806                    },
2807                    16.0,
2808                ),
2809                linear_color_stop(
2810                    Hsla {
2811                        h: 17.0,
2812                        s: 18.0,
2813                        l: 19.0,
2814                        a: 20.0,
2815                    },
2816                    21.0,
2817                ),
2818            )
2819            .color_space(ColorSpace::Oklab),
2820            border_color: Hsla {
2821                h: 22.0,
2822                s: 23.0,
2823                l: 24.0,
2824                a: 25.0,
2825            },
2826            corner_radii: Corners {
2827                top_left: 26.0.into(),
2828                top_right: 27.0.into(),
2829                bottom_right: 28.0.into(),
2830                bottom_left: 29.0.into(),
2831            },
2832            border_widths: Edges {
2833                top: 30.0.into(),
2834                right: 31.0.into(),
2835                bottom: 32.0.into(),
2836                left: 33.0.into(),
2837            },
2838        };
2839
2840        let bytes = unsafe { WgpuRendererCore::instance_bytes(std::slice::from_ref(&quad)) };
2841        let words: &[u32] = bytemuck::cast_slice(bytes);
2842        assert_eq!(
2843            words,
2844            &[
2845                41,
2846                1,
2847                1.0_f32.to_bits(),
2848                2.0_f32.to_bits(),
2849                3.0_f32.to_bits(),
2850                4.0_f32.to_bits(),
2851                5.0_f32.to_bits(),
2852                6.0_f32.to_bits(),
2853                7.0_f32.to_bits(),
2854                8.0_f32.to_bits(),
2855                1,
2856                1,
2857                0,
2858                0,
2859                0,
2860                0,
2861                11.0_f32.to_bits(),
2862                12.0_f32.to_bits(),
2863                13.0_f32.to_bits(),
2864                14.0_f32.to_bits(),
2865                15.0_f32.to_bits(),
2866                16.0_f32.to_bits(),
2867                17.0_f32.to_bits(),
2868                18.0_f32.to_bits(),
2869                19.0_f32.to_bits(),
2870                20.0_f32.to_bits(),
2871                21.0_f32.to_bits(),
2872                0,
2873                22.0_f32.to_bits(),
2874                23.0_f32.to_bits(),
2875                24.0_f32.to_bits(),
2876                25.0_f32.to_bits(),
2877                26.0_f32.to_bits(),
2878                27.0_f32.to_bits(),
2879                28.0_f32.to_bits(),
2880                29.0_f32.to_bits(),
2881                30.0_f32.to_bits(),
2882                31.0_f32.to_bits(),
2883                32.0_f32.to_bits(),
2884                33.0_f32.to_bits(),
2885            ]
2886        );
2887    }
2888}