Skip to main content

gpui_wgpu/
wgpu_renderer.rs

1// Modified for gpui-pre (snapshot of zed@f126950): 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                    // Native views are only composited by the Metal renderer.
1548                    PrimitiveBatch::NativeViews(_) => {}
1549                }
1550            }
1551        }
1552
1553        let submission = self
1554            .resources()
1555            .queue
1556            .submit(std::iter::once(encoder.finish()));
1557        Ok(submission)
1558    }
1559
1560    fn ensure_depth_texture(&mut self, size: Size<DevicePixels>) {
1561        let width = size.width.0 as u32;
1562        let height = size.height.0 as u32;
1563        if let Some(depth_texture) = &self.depth_texture
1564            && depth_texture.texture.width() == width
1565            && depth_texture.texture.height() == height
1566        {
1567            return;
1568        }
1569        let usage = if self.transient_attachments {
1570            wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TRANSIENT_ATTACHMENT
1571        } else {
1572            wgpu::TextureUsages::RENDER_ATTACHMENT
1573        };
1574        let texture = self
1575            .resources()
1576            .device
1577            .create_texture(&wgpu::TextureDescriptor {
1578                label: Some("depth_texture"),
1579                size: wgpu::Extent3d {
1580                    width,
1581                    height,
1582                    depth_or_array_layers: 1,
1583                },
1584                mip_level_count: 1,
1585                sample_count: 1,
1586                dimension: wgpu::TextureDimension::D2,
1587                format: DEPTH_FORMAT,
1588                usage,
1589                view_formats: &[],
1590            });
1591        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
1592        self.depth_texture = Some(DepthTexture { texture, view });
1593    }
1594
1595    fn write_instances(
1596        &mut self,
1597        scene: &Scene,
1598        instance_offset: &mut u64,
1599    ) -> Result<InstanceBindings> {
1600        Ok(InstanceBindings {
1601            quads: self.write_instance_binding(
1602                "quads_bind_group",
1603                instance_offset,
1604                &scene.quads,
1605            )?,
1606            shadows: self.write_instance_binding(
1607                "shadows_bind_group",
1608                instance_offset,
1609                &scene.shadows,
1610            )?,
1611            path_tiles: self.write_path_tiles(scene, instance_offset)?,
1612            underlines: self.write_instance_binding(
1613                "underlines_bind_group",
1614                instance_offset,
1615                &scene.underlines,
1616            )?,
1617            monochrome_sprites: self.write_instance_binding(
1618                "monochrome_sprites_bind_group",
1619                instance_offset,
1620                &scene.monochrome_sprites,
1621            )?,
1622            subpixel_sprites: self.write_instance_binding(
1623                "subpixel_sprites_bind_group",
1624                instance_offset,
1625                &scene.subpixel_sprites,
1626            )?,
1627            polychrome_sprites: self.write_instance_binding(
1628                "polychrome_sprites_bind_group",
1629                instance_offset,
1630                &scene.polychrome_sprites,
1631            )?,
1632        })
1633    }
1634
1635    fn create_texture_bind_group(
1636        &self,
1637        label: &str,
1638        texture_view: &wgpu::TextureView,
1639    ) -> wgpu::BindGroup {
1640        let resources = self.resources();
1641        resources
1642            .device
1643            .create_bind_group(&wgpu::BindGroupDescriptor {
1644                label: Some(label),
1645                layout: &resources.bind_group_layouts.texture,
1646                entries: &[
1647                    wgpu::BindGroupEntry {
1648                        binding: 0,
1649                        resource: wgpu::BindingResource::TextureView(texture_view),
1650                    },
1651                    wgpu::BindGroupEntry {
1652                        binding: 1,
1653                        resource: wgpu::BindingResource::Sampler(&resources.atlas_sampler),
1654                    },
1655                ],
1656            })
1657    }
1658
1659    fn prepare_texture_bind_groups(&mut self, scene: &Scene) {
1660        let mut texture_ids = SmallVec::<[AtlasTextureId; 8]>::new();
1661        for batch in scene.batches() {
1662            let texture_id = match batch {
1663                PrimitiveBatch::MonochromeSprites { texture_id, .. }
1664                | PrimitiveBatch::SubpixelSprites { texture_id, .. }
1665                | PrimitiveBatch::PolychromeSprites { texture_id, .. } => texture_id,
1666                _ => continue,
1667            };
1668            if !texture_ids.contains(&texture_id) {
1669                texture_ids.push(texture_id);
1670            }
1671        }
1672
1673        self.resources_mut()
1674            .atlas_texture_bind_groups
1675            .retain(|texture_id, _| texture_ids.contains(texture_id));
1676
1677        for texture_id in texture_ids {
1678            let Some(texture_info) = self.atlas.get_texture_info(texture_id) else {
1679                self.resources_mut()
1680                    .atlas_texture_bind_groups
1681                    .remove(&texture_id);
1682                continue;
1683            };
1684            let is_current = self
1685                .resources()
1686                .atlas_texture_bind_groups
1687                .get(&texture_id)
1688                .is_some_and(|cached| cached.texture_generation == texture_info.generation);
1689            if is_current {
1690                continue;
1691            }
1692
1693            let bind_group =
1694                self.create_texture_bind_group("atlas_texture_bind_group", &texture_info.view);
1695            self.resources_mut().atlas_texture_bind_groups.insert(
1696                texture_id,
1697                CachedTextureBindGroup {
1698                    texture_generation: texture_info.generation,
1699                    bind_group,
1700                },
1701            );
1702        }
1703    }
1704
1705    fn draw_instances(
1706        &self,
1707        instances: &InstanceBinding,
1708        pipeline: &wgpu::RenderPipeline,
1709        range: Range<u32>,
1710        pass: &mut wgpu::RenderPass<'_>,
1711    ) {
1712        if range.is_empty() {
1713            return;
1714        }
1715        pass.set_pipeline(pipeline);
1716        pass.set_bind_group(1, &instances.bind_group, &[]);
1717        pass.draw(
1718            0..4,
1719            instances.first_instance + range.start..instances.first_instance + range.end,
1720        );
1721    }
1722
1723    fn draw_sprites(
1724        &self,
1725        sprite_instances: &InstanceBinding,
1726        texture_id: AtlasTextureId,
1727        pipeline: &wgpu::RenderPipeline,
1728        range: Range<u32>,
1729        pass: &mut wgpu::RenderPass<'_>,
1730    ) -> Result<()> {
1731        if range.is_empty() {
1732            return Ok(());
1733        }
1734        let resources = self.resources();
1735        // The atlas has released this texture; the batch belongs to a stale
1736        // paint that will be replaced once its view re-renders.
1737        let Some(texture) = resources.atlas_texture_bind_groups.get(&texture_id) else {
1738            return Ok(());
1739        };
1740        pass.set_pipeline(pipeline);
1741        pass.set_bind_group(1, &sprite_instances.bind_group, &[]);
1742        pass.set_bind_group(2, &texture.bind_group, &[]);
1743        pass.draw(
1744            0..4,
1745            sprite_instances.first_instance + range.start
1746                ..sprite_instances.first_instance + range.end,
1747        );
1748        Ok(())
1749    }
1750
1751    unsafe fn instance_bytes<T>(instances: &[T]) -> &[u8] {
1752        unsafe {
1753            std::slice::from_raw_parts(
1754                instances.as_ptr() as *const u8,
1755                std::mem::size_of_val(instances),
1756            )
1757        }
1758    }
1759
1760    /// The alignment of an allocation of `byte_len` bytes of `stride`-sized
1761    /// records, and the bytes it takes up from that aligned offset.
1762    fn instance_allocation_layout(&self, stride: u64, byte_len: u64) -> (u64, u64) {
1763        // wgpu rejects zero-sized bindings, so empty primitive arrays still
1764        // reserve the 16-byte minimum.
1765        let size = byte_len.max(16);
1766        if self.uses_webgl_instance_data {
1767            // The texture transport has no binding offset: the shader indexes
1768            // the instance texture absolutely, so each allocation must start on
1769            // a whole instance (a stride multiple) and a whole texel, and must
1770            // end on a texel boundary so the zero padding of its final partial
1771            // texel cannot overlap the next allocation.
1772            (
1773                least_common_multiple(self.instance_data_alignment, stride),
1774                size.next_multiple_of(INSTANCE_TEXTURE_TEXEL_SIZE),
1775            )
1776        } else {
1777            (self.instance_data_alignment.max(1), size)
1778        }
1779    }
1780
1781    /// The most space `instances` can take up, including alignment padding.
1782    fn instance_allocation_bound<T>(&self, instances: &[T]) -> u64 {
1783        let stride = (std::mem::size_of::<T>() as u64).max(1);
1784        let (alignment, allocation_size) =
1785            self.instance_allocation_layout(stride, std::mem::size_of_val(instances) as u64);
1786        alignment + allocation_size
1787    }
1788
1789    /// Grows the instance data up front if `size` more bytes won't fit, so the
1790    /// allocations that follow land in the same buffer or texture.
1791    fn reserve_instance_data(&mut self, instance_offset: &mut u64, size: u64) -> Result<()> {
1792        if *instance_offset + size > self.instance_data_capacity {
1793            self.grow_instance_data(size)?;
1794            *instance_offset = 0;
1795        }
1796        Ok(())
1797    }
1798
1799    fn write_instance_data<T>(
1800        &mut self,
1801        instance_offset: &mut u64,
1802        instances: &[T],
1803    ) -> Result<InstanceAllocation> {
1804        let data = unsafe { Self::instance_bytes(instances) };
1805        let stride = (std::mem::size_of::<T>() as u64).max(1);
1806        let (alignment, allocation_size) =
1807            self.instance_allocation_layout(stride, data.len() as u64);
1808        let mut offset = (*instance_offset).next_multiple_of(alignment);
1809        if offset + allocation_size > self.instance_data_capacity {
1810            self.grow_instance_data(allocation_size)?;
1811            offset = 0;
1812        }
1813        *instance_offset = offset + allocation_size;
1814
1815        let first_instance = if self.uses_webgl_instance_data {
1816            u32::try_from(offset / stride).context("instance index exceeds u32 range")?
1817        } else {
1818            0
1819        };
1820
1821        let resources = self.resources();
1822        if !data.is_empty() {
1823            match &resources.instance_data {
1824                InstanceData::Storage(buffer) => resources.queue.write_buffer(buffer, offset, data),
1825                InstanceData::Texture { .. } => {
1826                    Self::write_instance_texture(resources, offset, data)
1827                }
1828            }
1829        }
1830        Ok(InstanceAllocation {
1831            offset,
1832            size: (data.len() as u64).max(16),
1833            first_instance,
1834        })
1835    }
1836
1837    fn instance_binding_resource(
1838        &self,
1839        allocation: &InstanceAllocation,
1840    ) -> wgpu::BindingResource<'_> {
1841        match &self.resources().instance_data {
1842            InstanceData::Storage(buffer) => wgpu::BindingResource::Buffer(wgpu::BufferBinding {
1843                buffer,
1844                offset: allocation.offset,
1845                size: NonZeroU64::new(allocation.size),
1846            }),
1847            InstanceData::Texture { view, .. } => wgpu::BindingResource::TextureView(view),
1848        }
1849    }
1850
1851    fn write_instance_binding<T>(
1852        &mut self,
1853        label: &str,
1854        instance_offset: &mut u64,
1855        instances: &[T],
1856    ) -> Result<InstanceBinding> {
1857        let allocation = self.write_instance_data(instance_offset, instances)?;
1858        let resources = self.resources();
1859        let bind_group = resources
1860            .device
1861            .create_bind_group(&wgpu::BindGroupDescriptor {
1862                label: Some(label),
1863                layout: &resources.bind_group_layouts.instances,
1864                entries: &[wgpu::BindGroupEntry {
1865                    binding: 0,
1866                    resource: self.instance_binding_resource(&allocation),
1867                }],
1868            });
1869        Ok(InstanceBinding {
1870            bind_group,
1871            first_instance: allocation.first_instance,
1872        })
1873    }
1874
1875    fn write_path_tiles(
1876        &mut self,
1877        scene: &Scene,
1878        instance_offset: &mut u64,
1879    ) -> Result<PathTileBinding> {
1880        let mut paint_data = Vec::with_capacity(scene.paths.len());
1881        let mut curve_data = Vec::new();
1882        let mut tile_data = Vec::new();
1883        for path in &scene.paths {
1884            path.append_to(&mut paint_data, &mut curve_data, &mut tile_data);
1885        }
1886
1887        // All three arrays are bound together, so they must not be split by a
1888        // grow partway through.
1889        let reserved = self.instance_allocation_bound(&paint_data)
1890            + self.instance_allocation_bound(&curve_data)
1891            + self.instance_allocation_bound(&tile_data);
1892        self.reserve_instance_data(instance_offset, reserved)?;
1893
1894        let paints = self.write_instance_data(instance_offset, &paint_data)?;
1895        let curves = self.write_instance_data(instance_offset, &curve_data)?;
1896        let tiles = self.write_instance_data(instance_offset, &tile_data)?;
1897
1898        let resources = self.resources();
1899        let bind_group = if self.uses_webgl_instance_data {
1900            resources
1901                .device
1902                .create_bind_group(&wgpu::BindGroupDescriptor {
1903                    label: Some("path_tiles_bind_group"),
1904                    layout: &resources.bind_group_layouts.path_tiles,
1905                    entries: &[wgpu::BindGroupEntry {
1906                        binding: 0,
1907                        resource: self.instance_binding_resource(&tiles),
1908                    }],
1909                })
1910        } else {
1911            resources
1912                .device
1913                .create_bind_group(&wgpu::BindGroupDescriptor {
1914                    label: Some("path_tiles_bind_group"),
1915                    layout: &resources.bind_group_layouts.path_tiles,
1916                    entries: &[
1917                        wgpu::BindGroupEntry {
1918                            binding: 0,
1919                            resource: self.instance_binding_resource(&tiles),
1920                        },
1921                        wgpu::BindGroupEntry {
1922                            binding: 1,
1923                            resource: self.instance_binding_resource(&curves),
1924                        },
1925                        wgpu::BindGroupEntry {
1926                            binding: 2,
1927                            resource: self.instance_binding_resource(&paints),
1928                        },
1929                    ],
1930                })
1931        };
1932        Ok(PathTileBinding {
1933            tiles: InstanceBinding {
1934                bind_group,
1935                first_instance: tiles.first_instance,
1936            },
1937            paint_base: paints.first_instance,
1938            curve_base: curves.first_instance,
1939        })
1940    }
1941
1942    fn write_instance_texture(resources: &WgpuResources, offset: u64, data: &[u8]) {
1943        let InstanceData::Texture {
1944            texture,
1945            width,
1946            height,
1947            ..
1948        } = &resources.instance_data
1949        else {
1950            return;
1951        };
1952        let mut byte_offset = 0usize;
1953        let mut texel_offset = offset / INSTANCE_TEXTURE_TEXEL_SIZE;
1954        while byte_offset < data.len() {
1955            let x = (texel_offset % u64::from(*width)) as u32;
1956            let y = (texel_offset / u64::from(*width)) as u32;
1957            if y >= *height {
1958                // The capacity check in write_instance_binding should make this
1959                // unreachable. Truncating silently would leave stale bytes in the
1960                // texture and draw garbage for the remaining instances.
1961                debug_assert!(
1962                    false,
1963                    "instance texture write out of bounds: row {y} >= height {}",
1964                    *height
1965                );
1966                log::error!(
1967                    "instance texture write out of bounds; dropping {} bytes of instance data",
1968                    data.len() - byte_offset
1969                );
1970                return;
1971            }
1972            let available_texels = u64::from(*width - x);
1973            let remaining_bytes = data.len() - byte_offset;
1974            let complete_texels = remaining_bytes as u64 / INSTANCE_TEXTURE_TEXEL_SIZE;
1975            let texels = complete_texels.min(available_texels);
1976            if texels > 0 {
1977                let byte_count = (texels * INSTANCE_TEXTURE_TEXEL_SIZE) as usize;
1978                resources.queue.write_texture(
1979                    wgpu::TexelCopyTextureInfo {
1980                        texture,
1981                        mip_level: 0,
1982                        origin: wgpu::Origin3d { x, y, z: 0 },
1983                        aspect: wgpu::TextureAspect::All,
1984                    },
1985                    &data[byte_offset..byte_offset + byte_count],
1986                    wgpu::TexelCopyBufferLayout {
1987                        offset: 0,
1988                        bytes_per_row: Some(byte_count as u32),
1989                        rows_per_image: None,
1990                    },
1991                    wgpu::Extent3d {
1992                        width: texels as u32,
1993                        height: 1,
1994                        depth_or_array_layers: 1,
1995                    },
1996                );
1997                byte_offset += byte_count;
1998                texel_offset += texels;
1999                continue;
2000            }
2001
2002            let mut final_texel = [0; INSTANCE_TEXTURE_TEXEL_SIZE as usize];
2003            final_texel[..remaining_bytes].copy_from_slice(&data[byte_offset..]);
2004            resources.queue.write_texture(
2005                wgpu::TexelCopyTextureInfo {
2006                    texture,
2007                    mip_level: 0,
2008                    origin: wgpu::Origin3d { x, y, z: 0 },
2009                    aspect: wgpu::TextureAspect::All,
2010                },
2011                &final_texel,
2012                wgpu::TexelCopyBufferLayout {
2013                    offset: 0,
2014                    bytes_per_row: Some(INSTANCE_TEXTURE_TEXEL_SIZE as u32),
2015                    rows_per_image: None,
2016                },
2017                wgpu::Extent3d {
2018                    width: 1,
2019                    height: 1,
2020                    depth_or_array_layers: 1,
2021                },
2022            );
2023            break;
2024        }
2025    }
2026
2027    fn grow_instance_data(&mut self, required: u64) -> Result<()> {
2028        let capacity = (self.instance_data_capacity * 2)
2029            .max(required.next_power_of_two())
2030            .min(self.max_instance_data_size);
2031        anyhow::ensure!(
2032            capacity >= required,
2033            "instance data needs {required} bytes, above the maximum of {}",
2034            self.max_instance_data_size
2035        );
2036        anyhow::ensure!(
2037            capacity > self.instance_data_capacity,
2038            "frame instance data exceeds the {}-byte maximum",
2039            self.max_instance_data_size
2040        );
2041        log::debug!(
2042            "instance data grown from {} to {capacity}",
2043            self.instance_data_capacity
2044        );
2045        // Bind groups created earlier in the frame keep the previous buffer or
2046        // texture alive, so allocations written before the grow remain valid;
2047        // only subsequent writes land in the new allocation.
2048        let uses_webgl_instance_data = self.uses_webgl_instance_data;
2049        let resources = self.resources_mut();
2050        if uses_webgl_instance_data {
2051            let max_texture_dimension = resources.device.limits().max_texture_dimension_2d;
2052            let (instance_data, actual_capacity) =
2053                Self::create_instance_texture(&resources.device, capacity, max_texture_dimension);
2054            resources.instance_data = instance_data;
2055            self.instance_data_capacity = actual_capacity;
2056        } else {
2057            resources.instance_data =
2058                InstanceData::Storage(resources.device.create_buffer(&wgpu::BufferDescriptor {
2059                    label: Some("instance_buffer"),
2060                    size: capacity,
2061                    usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
2062                    mapped_at_creation: false,
2063                }));
2064            self.instance_data_capacity = capacity;
2065        }
2066        Ok(())
2067    }
2068}
2069
2070impl WgpuRenderer {
2071    /// Mark the surface as unconfigured so rendering is skipped until a new
2072    /// surface is provided via [`replace_surface`](Self::replace_surface).
2073    ///
2074    /// This does **not** drop the renderer — the device, queue, atlas, and
2075    /// pipelines stay alive.  Use this when the native window is destroyed
2076    /// (e.g. Android `TerminateWindow`) but you intend to re-create the
2077    /// surface later without losing cached atlas textures.
2078    pub fn unconfigure_surface(&mut self) {
2079        self.state = match std::mem::replace(&mut self.state, RendererState::Released) {
2080            RendererState::Ready { core, surface } => {
2081                drop(surface);
2082                RendererState::Unconfigured { core }
2083            }
2084            state @ (RendererState::Unconfigured { .. } | RendererState::Released) => state,
2085        };
2086    }
2087
2088    /// Replace the wgpu surface with a new one (e.g. after Android destroys
2089    /// and recreates the native window).  Keeps the device, queue, atlas, and
2090    /// all pipelines intact so cached `AtlasTextureId`s remain valid.
2091    ///
2092    /// The `instance` **must** be the same [`wgpu::Instance`] that was used to
2093    /// create the adapter and device (i.e. from the [`WgpuContext`]).  Using a
2094    /// different instance will cause a "Device does not exist" panic because
2095    /// the wgpu device is bound to its originating instance.
2096    #[cfg(not(target_family = "wasm"))]
2097    pub fn replace_surface<W: HasWindowHandle>(
2098        &mut self,
2099        window: &W,
2100        config: WgpuSurfaceConfig,
2101        instance: &wgpu::Instance,
2102    ) -> anyhow::Result<()> {
2103        let window_handle = window
2104            .window_handle()
2105            .map_err(|e| anyhow::anyhow!("Failed to get window handle: {e}"))?;
2106
2107        let surface = create_surface(instance, window_handle.as_raw())?;
2108
2109        let width = (config.size.width.0 as u32).max(1);
2110        let height = (config.size.height.0 as u32).max(1);
2111
2112        let alpha_mode = if config.transparent {
2113            self.transparent_alpha_mode
2114        } else {
2115            self.opaque_alpha_mode
2116        };
2117        let alpha_mode_changed = alpha_mode != self.surface_config.alpha_mode;
2118
2119        self.surface_config.width = width;
2120        self.surface_config.height = height;
2121        self.surface_config.alpha_mode = alpha_mode;
2122        if let Some(mode) = config.preferred_present_mode {
2123            self.surface_config.present_mode = mode;
2124        }
2125
2126        let mut core = match std::mem::replace(&mut self.state, RendererState::Released) {
2127            RendererState::Ready {
2128                core,
2129                surface: old_surface,
2130            } => {
2131                drop(old_surface);
2132                core
2133            }
2134            RendererState::Unconfigured { core } => core,
2135            RendererState::Released => {
2136                anyhow::bail!("Cannot replace the surface: GPU resources have been released")
2137            }
2138        };
2139        if alpha_mode_changed {
2140            core.rebuild_pipelines(self.surface_config.format, alpha_mode);
2141        }
2142        surface.configure(&core.resources.device, &self.surface_config);
2143        self.state = RendererState::Ready { surface, core };
2144
2145        Ok(())
2146    }
2147
2148    pub fn destroy(&mut self) {
2149        // Release surface-bound GPU resources eagerly so the underlying native
2150        // window can be destroyed before the renderer itself is dropped.
2151        self.state = RendererState::Released;
2152    }
2153
2154    /// Returns true if the GPU device was lost and recovery is needed.
2155    pub fn device_lost(&self) -> bool {
2156        self.device_errors.device_lost()
2157    }
2158
2159    /// Returns true if a redraw is needed because GPU state was cleared.
2160    /// Calling this method clears the flag.
2161    pub fn needs_redraw(&mut self) -> bool {
2162        std::mem::take(&mut self.needs_redraw)
2163    }
2164
2165    /// Recovers from a lost GPU device by recreating the renderer with a new context.
2166    ///
2167    /// Call this after detecting `device_lost()` returns true.
2168    ///
2169    /// This method coordinates recovery across multiple windows:
2170    /// - The first window to call this will recreate the shared context
2171    /// - Subsequent windows will adopt the already-recovered context
2172    #[cfg(not(target_family = "wasm"))]
2173    pub fn recover<W>(&mut self, window: &W) -> anyhow::Result<()>
2174    where
2175        W: HasWindowHandle + HasDisplayHandle + std::fmt::Debug + Send + Sync + Clone + 'static,
2176    {
2177        let gpu_context = self.context.as_ref().expect("recover requires gpu_context");
2178
2179        // Check if another window already recovered the context
2180        let needs_new_context = gpu_context
2181            .borrow()
2182            .as_ref()
2183            .is_none_or(|ctx| ctx.device_lost());
2184
2185        let window_handle = window
2186            .window_handle()
2187            .map_err(|e| anyhow::anyhow!("Failed to get window handle: {e}"))?;
2188
2189        let config = WgpuSurfaceConfig {
2190            size: gpui::Size {
2191                width: gpui::DevicePixels(self.surface_config.width as i32),
2192                height: gpui::DevicePixels(self.surface_config.height as i32),
2193            },
2194            transparent: self.surface_config.alpha_mode != wgpu::CompositeAlphaMode::Opaque,
2195            preferred_present_mode: Some(self.surface_config.present_mode),
2196        };
2197
2198        let surface = if needs_new_context {
2199            log::warn!("GPU device lost, recreating context...");
2200
2201            // Drop old resources to release Arc<Device>/Arc<Queue> and GPU resources
2202            self.state = RendererState::Released;
2203            *gpu_context.borrow_mut() = None;
2204
2205            // Wait briefly for the GPU driver to stabilize, then try to
2206            // recreate the context without software renderers. If this fails
2207            // the caller should request another frame and retry — the real GPU
2208            // may need more time to come back (e.g. after suspend/resume).
2209            std::thread::sleep(std::time::Duration::from_millis(350));
2210
2211            let instance = WgpuContext::instance(Some(Box::new(window.clone())));
2212            let surface = create_surface(&instance, window_handle.as_raw())?;
2213            let new_context = WgpuContext::new_rejecting_software(
2214                instance,
2215                &surface,
2216                &config,
2217                self.compositor_gpu,
2218            )?;
2219            *gpu_context.borrow_mut() = Some(new_context);
2220            surface
2221        } else {
2222            let ctx_ref = gpu_context.borrow();
2223            let instance = &ctx_ref.as_ref().unwrap().instance;
2224            create_surface(instance, window_handle.as_raw())?
2225        };
2226
2227        let gpu_context = Rc::clone(gpu_context);
2228        let ctx_ref = gpu_context.borrow();
2229        let context = ctx_ref.as_ref().expect("context should exist");
2230
2231        self.state = RendererState::Released;
2232        self.atlas.handle_device_lost(context);
2233
2234        let is_bgr = self.is_bgr;
2235        *self = Self::new_internal(
2236            Some(gpu_context.clone()),
2237            context,
2238            surface,
2239            config,
2240            needs_new_context,
2241            self.compositor_gpu,
2242            self.atlas.clone(),
2243        )?;
2244        self.set_subpixel_layout(is_bgr);
2245
2246        log::info!("GPU recovery complete");
2247        Ok(())
2248    }
2249}
2250
2251#[cfg(all(
2252    not(target_family = "wasm"),
2253    any(test, feature = "bench-support", feature = "test-support")
2254))]
2255struct HeadlessRenderTarget {
2256    texture: wgpu::Texture,
2257    view: wgpu::TextureView,
2258}
2259
2260#[cfg(all(
2261    not(target_family = "wasm"),
2262    any(test, feature = "bench-support", feature = "test-support")
2263))]
2264impl HeadlessRenderTarget {
2265    fn size(&self) -> Size<DevicePixels> {
2266        Size {
2267            width: DevicePixels(self.texture.width() as i32),
2268            height: DevicePixels(self.texture.height() as i32),
2269        }
2270    }
2271}
2272
2273#[cfg(all(
2274    not(target_family = "wasm"),
2275    any(test, feature = "bench-support", feature = "test-support")
2276))]
2277pub struct WgpuHeadlessRenderer {
2278    context: WgpuContext,
2279    core: WgpuRendererCore,
2280    render_target: Option<HeadlessRenderTarget>,
2281    observed_error_generation: u64,
2282}
2283
2284#[cfg(all(
2285    not(target_family = "wasm"),
2286    any(test, feature = "bench-support", feature = "test-support")
2287))]
2288impl WgpuHeadlessRenderer {
2289    pub fn new() -> anyhow::Result<Self> {
2290        let (context, target_format) = WgpuContext::new_headless()?;
2291        // The device may be shared with earlier renderers; observe only errors raised from
2292        // here on, including any while this renderer builds its pipelines.
2293        let observed_error_generation = context.errors().current_generation();
2294        let atlas = Arc::new(WgpuAtlas::from_context(&context));
2295        let core = WgpuRendererCore::new(
2296            &context,
2297            atlas,
2298            target_format,
2299            wgpu::CompositeAlphaMode::Opaque,
2300        );
2301
2302        Ok(Self {
2303            context,
2304            core,
2305            render_target: None,
2306            observed_error_generation,
2307        })
2308    }
2309
2310    fn ensure_render_target(&mut self, size: Size<DevicePixels>) -> anyhow::Result<()> {
2311        anyhow::ensure!(
2312            size.width.0 > 0 && size.height.0 > 0,
2313            "invalid headless render target size: {size:?}"
2314        );
2315        anyhow::ensure!(
2316            size.width.0 as u32 <= self.core.max_texture_size
2317                && size.height.0 as u32 <= self.core.max_texture_size,
2318            "headless render target size {size:?} exceeds maximum texture dimension {}",
2319            self.core.max_texture_size
2320        );
2321        if self
2322            .render_target
2323            .as_ref()
2324            .is_some_and(|target| target.size() == size)
2325        {
2326            return Ok(());
2327        }
2328
2329        let texture = self
2330            .core
2331            .resources
2332            .device
2333            .create_texture(&wgpu::TextureDescriptor {
2334                label: Some("headless_render_target"),
2335                size: wgpu::Extent3d {
2336                    width: size.width.0 as u32,
2337                    height: size.height.0 as u32,
2338                    depth_or_array_layers: 1,
2339                },
2340                mip_level_count: 1,
2341                sample_count: 1,
2342                dimension: wgpu::TextureDimension::D2,
2343                format: self.core.target_format,
2344                usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
2345                view_formats: &[],
2346            });
2347        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
2348        self.render_target = Some(HeadlessRenderTarget { texture, view });
2349        Ok(())
2350    }
2351
2352    fn check_gpu_errors(&mut self) -> anyhow::Result<()> {
2353        anyhow::ensure!(
2354            !self.context.device_lost(),
2355            "GPU device was lost during headless rendering"
2356        );
2357        if let Some(error) = self
2358            .context
2359            .errors()
2360            .observe_error(&mut self.observed_error_generation)
2361        {
2362            anyhow::bail!("GPU error during headless rendering: {error}");
2363        }
2364        Ok(())
2365    }
2366
2367    fn render(&mut self, scene: &Scene, size: Size<DevicePixels>) -> anyhow::Result<()> {
2368        self.check_gpu_errors()?;
2369        self.ensure_render_target(size)?;
2370        let view = self
2371            .render_target
2372            .as_ref()
2373            .ok_or_else(|| anyhow::anyhow!("Headless render target was not created"))?
2374            .view
2375            .clone();
2376        self.core
2377            .render_frame(scene, &view, size, wgpu::Color::BLACK)?;
2378        Ok(())
2379    }
2380
2381    /// Copies the current render target back to the CPU. Dimensions come from the
2382    /// target texture itself, so the copy can never disagree with what was rendered.
2383    fn read_image(&mut self) -> anyhow::Result<image::RgbaImage> {
2384        let target = self
2385            .render_target
2386            .as_ref()
2387            .ok_or_else(|| anyhow::anyhow!("Headless render target was not created"))?;
2388        let width = target.texture.width();
2389        let height = target.texture.height();
2390        let bytes_per_row = width
2391            .checked_mul(4)
2392            .ok_or_else(|| anyhow::anyhow!("Headless render target row size overflowed"))?;
2393        let padded_bytes_per_row = bytes_per_row
2394            .checked_next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
2395            .ok_or_else(|| anyhow::anyhow!("Headless padded row size overflowed"))?;
2396        let buffer_size = u64::from(padded_bytes_per_row)
2397            .checked_mul(u64::from(height))
2398            .ok_or_else(|| anyhow::anyhow!("Headless readback buffer size overflowed"))?;
2399        anyhow::ensure!(
2400            buffer_size <= self.core.resources.device.limits().max_buffer_size,
2401            "Headless readback buffer size {buffer_size} exceeds maximum buffer size {}",
2402            self.core.resources.device.limits().max_buffer_size
2403        );
2404        let readback_buffer = self
2405            .core
2406            .resources
2407            .device
2408            .create_buffer(&wgpu::BufferDescriptor {
2409                label: Some("headless_readback_buffer"),
2410                size: buffer_size,
2411                usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
2412                mapped_at_creation: false,
2413            });
2414        let mut encoder =
2415            self.core
2416                .resources
2417                .device
2418                .create_command_encoder(&wgpu::CommandEncoderDescriptor {
2419                    label: Some("headless_readback_encoder"),
2420                });
2421        encoder.copy_texture_to_buffer(
2422            wgpu::TexelCopyTextureInfo {
2423                texture: &target.texture,
2424                mip_level: 0,
2425                origin: wgpu::Origin3d::ZERO,
2426                aspect: wgpu::TextureAspect::All,
2427            },
2428            wgpu::TexelCopyBufferInfo {
2429                buffer: &readback_buffer,
2430                layout: wgpu::TexelCopyBufferLayout {
2431                    offset: 0,
2432                    bytes_per_row: Some(padded_bytes_per_row),
2433                    rows_per_image: Some(height),
2434                },
2435            },
2436            wgpu::Extent3d {
2437                width,
2438                height,
2439                depth_or_array_layers: 1,
2440            },
2441        );
2442        let submission = self
2443            .core
2444            .resources
2445            .queue
2446            .submit(std::iter::once(encoder.finish()));
2447        let (sender, receiver) = std::sync::mpsc::channel();
2448        readback_buffer
2449            .slice(..)
2450            .map_async(wgpu::MapMode::Read, move |result| {
2451                if sender.send(result).is_err() {
2452                    log::error!("Headless readback receiver was dropped before mapping completed");
2453                }
2454            });
2455        self.core
2456            .resources
2457            .device
2458            .poll(wgpu::PollType::Wait {
2459                submission_index: Some(submission),
2460                timeout: Some(std::time::Duration::from_secs(30)),
2461            })
2462            .map_err(|error| anyhow::anyhow!("Failed to wait for headless rendering: {error}"))?;
2463        receiver
2464            .recv_timeout(std::time::Duration::from_secs(30))
2465            .map_err(|error| anyhow::anyhow!("Failed to receive headless mapping result: {error}"))?
2466            .map_err(|error| anyhow::anyhow!("Failed to map headless readback buffer: {error}"))?;
2467        self.check_gpu_errors()?;
2468
2469        let mapped_data = readback_buffer.slice(..).get_mapped_range()?;
2470        let pixel_capacity = usize::try_from(u64::from(bytes_per_row) * u64::from(height))
2471            .map_err(|_| anyhow::anyhow!("Headless image size exceeds addressable memory"))?;
2472        let mut pixels = Vec::with_capacity(pixel_capacity);
2473        for row in mapped_data
2474            .chunks_exact(padded_bytes_per_row as usize)
2475            .take(height as usize)
2476        {
2477            pixels.extend_from_slice(&row[..bytes_per_row as usize]);
2478        }
2479        drop(mapped_data);
2480        readback_buffer.unmap();
2481
2482        if self.core.target_format == wgpu::TextureFormat::Bgra8Unorm {
2483            for pixel in pixels.chunks_exact_mut(4) {
2484                pixel.swap(0, 2);
2485            }
2486        }
2487
2488        image::RgbaImage::from_raw(width, height, pixels)
2489            .ok_or_else(|| anyhow::anyhow!("Failed to create image from headless pixel data"))
2490    }
2491}
2492
2493#[cfg(all(
2494    not(target_family = "wasm"),
2495    any(test, feature = "bench-support", feature = "test-support")
2496))]
2497impl gpui::PlatformHeadlessRenderer for WgpuHeadlessRenderer {
2498    fn render_scene_to_image(
2499        &mut self,
2500        scene: &Scene,
2501        size: Size<DevicePixels>,
2502    ) -> anyhow::Result<image::RgbaImage> {
2503        self.render(scene, size)?;
2504        self.read_image()
2505    }
2506
2507    fn render_scene(&mut self, scene: &Scene, size: Size<DevicePixels>) -> anyhow::Result<()> {
2508        self.render(scene, size)
2509    }
2510
2511    fn sprite_atlas(&self) -> Arc<dyn gpui::PlatformAtlas> {
2512        self.core.atlas.clone()
2513    }
2514}
2515
2516fn instance_range(range: Range<usize>) -> Range<u32> {
2517    range.start as u32..range.end as u32
2518}
2519
2520#[cfg(not(target_family = "wasm"))]
2521fn create_surface(
2522    instance: &wgpu::Instance,
2523    raw_window_handle: raw_window_handle::RawWindowHandle,
2524) -> anyhow::Result<wgpu::Surface<'static>> {
2525    unsafe {
2526        instance
2527            .create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle {
2528                // Fall back to the display handle already provided via InstanceDescriptor::display.
2529                raw_display_handle: None,
2530                raw_window_handle,
2531            })
2532            .map_err(|e| anyhow::anyhow!("{e}"))
2533    }
2534}
2535
2536struct RenderingParameters {
2537    gamma_ratios: [f32; 4],
2538    grayscale_enhanced_contrast: f32,
2539    subpixel_enhanced_contrast: f32,
2540}
2541
2542impl RenderingParameters {
2543    fn new() -> Self {
2544        use std::env;
2545
2546        let gamma = env::var("ZED_FONTS_GAMMA")
2547            .ok()
2548            .and_then(|v| v.parse().ok())
2549            .unwrap_or(1.8_f32)
2550            .clamp(1.0, 2.2);
2551        let gamma_ratios = get_gamma_correction_ratios(gamma);
2552
2553        let grayscale_enhanced_contrast = env::var("ZED_FONTS_GRAYSCALE_ENHANCED_CONTRAST")
2554            .ok()
2555            .and_then(|v| v.parse().ok())
2556            .unwrap_or(1.0_f32)
2557            .max(0.0);
2558
2559        let subpixel_enhanced_contrast = env::var("ZED_FONTS_SUBPIXEL_ENHANCED_CONTRAST")
2560            .ok()
2561            .and_then(|v| v.parse().ok())
2562            .unwrap_or(0.5_f32)
2563            .max(0.0);
2564
2565        Self {
2566            gamma_ratios,
2567            grayscale_enhanced_contrast,
2568            subpixel_enhanced_contrast,
2569        }
2570    }
2571}
2572
2573#[cfg(test)]
2574mod tests {
2575    use super::*;
2576    use gpui::{
2577        BorderStyle, ColorSpace, ContentMask, Corners, Edges, Hsla, MonochromeSprite, PathCurve,
2578        PathPaint, PathTile, Point, PolychromeSprite, Quad, Shadow, Size, SubpixelSprite,
2579        Underline, linear_color_stop, linear_gradient,
2580    };
2581    #[cfg(target_os = "linux")]
2582    use gpui::{DevicePixels, PlatformHeadlessRenderer, Scene};
2583
2584    #[cfg(target_os = "linux")]
2585    fn device_size(width: i32, height: i32) -> Size<DevicePixels> {
2586        Size {
2587            width: DevicePixels(width),
2588            height: DevicePixels(height),
2589        }
2590    }
2591
2592    #[cfg(target_os = "linux")]
2593    fn solid_quad(x: f32, y: f32, width: f32, height: f32, color: Hsla) -> Quad {
2594        let bounds = Bounds {
2595            origin: Point {
2596                x: x.into(),
2597                y: y.into(),
2598            },
2599            size: Size {
2600                width: width.into(),
2601                height: height.into(),
2602            },
2603        };
2604        Quad {
2605            order: 0,
2606            border_style: BorderStyle::Solid,
2607            bounds,
2608            content_mask: ContentMask { bounds },
2609            background: color.into(),
2610            border_color: color,
2611            corner_radii: Corners::default(),
2612            border_widths: Edges::default(),
2613        }
2614    }
2615
2616    /// Channels are compared with a small tolerance so the assertions hold across
2617    /// drivers without pinning exact rasterizer output.
2618    #[cfg(target_os = "linux")]
2619    fn assert_pixel(image: &image::RgbaImage, x: u32, y: u32, expected: [u8; 4]) {
2620        let actual = image.get_pixel(x, y).0;
2621        assert!(
2622            actual
2623                .iter()
2624                .zip(expected)
2625                .all(|(actual, expected)| actual.abs_diff(expected) <= 3),
2626            "pixel ({x}, {y}) was {actual:?}, expected {expected:?}"
2627        );
2628    }
2629
2630    #[cfg(target_os = "linux")]
2631    const RED: [u8; 4] = [255, 0, 0, 255];
2632    #[cfg(target_os = "linux")]
2633    const BLUE: [u8; 4] = [0, 0, 255, 255];
2634    #[cfg(target_os = "linux")]
2635    const BLACK: [u8; 4] = [0, 0, 0, 255];
2636
2637    #[cfg(target_os = "linux")]
2638    #[test]
2639    fn headless_renderer_draws_quads_with_distinct_colors() -> anyhow::Result<()> {
2640        let mut renderer = WgpuHeadlessRenderer::new()?;
2641        let mut scene = Scene::default();
2642        scene.insert_primitive(solid_quad(0.0, 0.0, 32.0, 32.0, gpui::red()));
2643        scene.insert_primitive(solid_quad(32.0, 0.0, 32.0, 32.0, gpui::blue()));
2644        scene.finish();
2645
2646        let image = renderer.render_scene_to_image(&scene, device_size(64, 32))?;
2647        assert_eq!(image.dimensions(), (64, 32));
2648        assert_pixel(&image, 8, 16, RED);
2649        assert_pixel(&image, 24, 16, RED);
2650        assert_pixel(&image, 40, 16, BLUE);
2651        assert_pixel(&image, 56, 16, BLUE);
2652        Ok(())
2653    }
2654
2655    #[cfg(target_os = "linux")]
2656    #[test]
2657    fn headless_renderer_captures_each_requested_size() -> anyhow::Result<()> {
2658        let mut renderer = WgpuHeadlessRenderer::new()?;
2659        let mut scene = Scene::default();
2660        scene.insert_primitive(solid_quad(2.0, 2.0, 4.0, 3.0, gpui::red()));
2661        scene.finish();
2662
2663        // 13 px rows are 52 bytes, forcing readback to strip copy-row padding.
2664        let image = renderer.render_scene_to_image(&scene, device_size(13, 7))?;
2665        assert_eq!(image.dimensions(), (13, 7));
2666        assert_pixel(&image, 0, 0, BLACK);
2667        assert_pixel(&image, 3, 3, RED);
2668        assert_pixel(&image, 12, 6, BLACK);
2669
2670        let image = renderer.render_scene_to_image(&scene, device_size(17, 9))?;
2671        assert_eq!(image.dimensions(), (17, 9));
2672        assert_pixel(&image, 3, 3, RED);
2673        assert_pixel(&image, 16, 8, BLACK);
2674
2675        let image = renderer.render_scene_to_image(&Scene::default(), device_size(13, 7))?;
2676        assert_eq!(image.dimensions(), (13, 7));
2677        assert!(image.pixels().all(|pixel| pixel.0 == BLACK));
2678        Ok(())
2679    }
2680
2681    #[cfg(target_os = "linux")]
2682    #[test]
2683    fn headless_renderer_reuses_target_for_same_size() -> anyhow::Result<()> {
2684        let mut renderer = WgpuHeadlessRenderer::new()?;
2685        let target_texture = |renderer: &WgpuHeadlessRenderer| {
2686            renderer
2687                .render_target
2688                .as_ref()
2689                .map(|target| target.texture.clone())
2690        };
2691
2692        renderer.render_scene(&Scene::default(), device_size(16, 16))?;
2693        let first = target_texture(&renderer);
2694        assert!(first.is_some());
2695
2696        renderer.render_scene(&Scene::default(), device_size(16, 16))?;
2697        assert_eq!(target_texture(&renderer), first);
2698
2699        renderer.render_scene(&Scene::default(), device_size(16, 17))?;
2700        assert_ne!(target_texture(&renderer), first);
2701        Ok(())
2702    }
2703
2704    #[cfg(target_os = "linux")]
2705    #[test]
2706    fn headless_renderer_rejects_invalid_sizes() -> anyhow::Result<()> {
2707        let mut renderer = WgpuHeadlessRenderer::new()?;
2708        let too_large = renderer.core.max_texture_size as i32 + 1;
2709
2710        for size in [
2711            device_size(0, 8),
2712            device_size(8, 0),
2713            device_size(-1, 8),
2714            device_size(too_large, 8),
2715        ] {
2716            assert!(
2717                renderer.render_scene(&Scene::default(), size).is_err(),
2718                "{size:?} should be rejected"
2719            );
2720            assert!(
2721                renderer
2722                    .render_scene_to_image(&Scene::default(), size)
2723                    .is_err(),
2724                "{size:?} should be rejected"
2725            );
2726        }
2727
2728        // Rejection must leave the renderer usable.
2729        let image = renderer.render_scene_to_image(&Scene::default(), device_size(4, 4))?;
2730        assert_eq!(image.dimensions(), (4, 4));
2731        Ok(())
2732    }
2733
2734    #[test]
2735    fn webgl_shader_is_valid_wgsl_without_storage_buffers() {
2736        assert!(!WEBGL_SHADERS.contains("var<storage"));
2737        validate_wgsl(WEBGL_SHADERS, naga::valid::Capabilities::empty());
2738    }
2739
2740    #[test]
2741    fn storage_buffer_shader_is_valid_wgsl() {
2742        validate_wgsl(STORAGE_BUFFER_SHADERS, naga::valid::Capabilities::empty());
2743    }
2744
2745    #[test]
2746    fn subpixel_shader_is_valid_wgsl() {
2747        validate_wgsl(
2748            SUBPIXEL_SHADERS,
2749            naga::valid::Capabilities::DUAL_SOURCE_BLENDING,
2750        );
2751    }
2752
2753    fn validate_wgsl(source: &str, capabilities: naga::valid::Capabilities) {
2754        let module = naga::front::wgsl::parse_str(source).expect("shader should parse");
2755        naga::valid::Validator::new(naga::valid::ValidationFlags::all(), capabilities)
2756            .validate(&module)
2757            .expect("shader should validate");
2758    }
2759
2760    #[test]
2761    fn webgl_record_sizes_match_shader_word_strides() {
2762        assert_eq!(std::mem::size_of::<Quad>(), 40 * 4);
2763        assert_eq!(std::mem::size_of::<Shadow>(), 28 * 4);
2764        assert_eq!(std::mem::size_of::<PathTile>(), 14 * 4);
2765        assert_eq!(std::mem::size_of::<PathCurve>(), 10 * 4);
2766        assert_eq!(std::mem::size_of::<PathPaint>(), 28 * 4);
2767        assert_eq!(std::mem::size_of::<Underline>(), 16 * 4);
2768        assert_eq!(std::mem::size_of::<MonochromeSprite>(), 28 * 4);
2769        assert_eq!(std::mem::size_of::<SubpixelSprite>(), 28 * 4);
2770        assert_eq!(std::mem::size_of::<PolychromeSprite>(), 24 * 4);
2771    }
2772
2773    #[test]
2774    fn webgl_quad_layout_matches_fixed_decoder() {
2775        let quad = Quad {
2776            order: 41,
2777            border_style: BorderStyle::Dashed,
2778            bounds: Bounds {
2779                origin: Point {
2780                    x: 1.0.into(),
2781                    y: 2.0.into(),
2782                },
2783                size: Size {
2784                    width: 3.0.into(),
2785                    height: 4.0.into(),
2786                },
2787            },
2788            content_mask: ContentMask {
2789                bounds: Bounds {
2790                    origin: Point {
2791                        x: 5.0.into(),
2792                        y: 6.0.into(),
2793                    },
2794                    size: Size {
2795                        width: 7.0.into(),
2796                        height: 8.0.into(),
2797                    },
2798                },
2799            },
2800            background: linear_gradient(
2801                11.0,
2802                linear_color_stop(
2803                    Hsla {
2804                        h: 12.0,
2805                        s: 13.0,
2806                        l: 14.0,
2807                        a: 15.0,
2808                    },
2809                    16.0,
2810                ),
2811                linear_color_stop(
2812                    Hsla {
2813                        h: 17.0,
2814                        s: 18.0,
2815                        l: 19.0,
2816                        a: 20.0,
2817                    },
2818                    21.0,
2819                ),
2820            )
2821            .color_space(ColorSpace::Oklab),
2822            border_color: Hsla {
2823                h: 22.0,
2824                s: 23.0,
2825                l: 24.0,
2826                a: 25.0,
2827            },
2828            corner_radii: Corners {
2829                top_left: 26.0.into(),
2830                top_right: 27.0.into(),
2831                bottom_right: 28.0.into(),
2832                bottom_left: 29.0.into(),
2833            },
2834            border_widths: Edges {
2835                top: 30.0.into(),
2836                right: 31.0.into(),
2837                bottom: 32.0.into(),
2838                left: 33.0.into(),
2839            },
2840        };
2841
2842        let bytes = unsafe { WgpuRendererCore::instance_bytes(std::slice::from_ref(&quad)) };
2843        let words: &[u32] = bytemuck::cast_slice(bytes);
2844        assert_eq!(
2845            words,
2846            &[
2847                41,
2848                1,
2849                1.0_f32.to_bits(),
2850                2.0_f32.to_bits(),
2851                3.0_f32.to_bits(),
2852                4.0_f32.to_bits(),
2853                5.0_f32.to_bits(),
2854                6.0_f32.to_bits(),
2855                7.0_f32.to_bits(),
2856                8.0_f32.to_bits(),
2857                1,
2858                1,
2859                0,
2860                0,
2861                0,
2862                0,
2863                11.0_f32.to_bits(),
2864                12.0_f32.to_bits(),
2865                13.0_f32.to_bits(),
2866                14.0_f32.to_bits(),
2867                15.0_f32.to_bits(),
2868                16.0_f32.to_bits(),
2869                17.0_f32.to_bits(),
2870                18.0_f32.to_bits(),
2871                19.0_f32.to_bits(),
2872                20.0_f32.to_bits(),
2873                21.0_f32.to_bits(),
2874                0,
2875                22.0_f32.to_bits(),
2876                23.0_f32.to_bits(),
2877                24.0_f32.to_bits(),
2878                25.0_f32.to_bits(),
2879                26.0_f32.to_bits(),
2880                27.0_f32.to_bits(),
2881                28.0_f32.to_bits(),
2882                29.0_f32.to_bits(),
2883                30.0_f32.to_bits(),
2884                31.0_f32.to_bits(),
2885                32.0_f32.to_bits(),
2886                33.0_f32.to_bits(),
2887            ]
2888        );
2889    }
2890}