Skip to main content

gpui_wgpu/
wgpu_renderer.rs

1use crate::{CompositorGpuHint, WgpuAtlas, WgpuContext};
2use bytemuck::{Pod, Zeroable};
3use gpui::{
4    AtlasTextureId, Background, Bounds, DevicePixels, GpuSpecs, MonochromeSprite, Path, Point,
5    PolychromeSprite, PrimitiveBatch, Quad, ScaledPixels, Scene, Shadow, Size, SubpixelSprite,
6    Underline, get_gamma_correction_ratios,
7};
8use log::warn;
9#[cfg(not(target_family = "wasm"))]
10use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
11use std::cell::RefCell;
12use std::num::NonZeroU64;
13use std::rc::Rc;
14use std::sync::{Arc, Mutex};
15
16#[repr(C)]
17#[derive(Clone, Copy, Pod, Zeroable)]
18struct GlobalParams {
19    viewport_size: [f32; 2],
20    premultiplied_alpha: u32,
21    pad: u32,
22}
23
24#[repr(C)]
25#[derive(Clone, Copy, Pod, Zeroable)]
26struct PodBounds {
27    origin: [f32; 2],
28    size: [f32; 2],
29}
30
31impl From<Bounds<ScaledPixels>> for PodBounds {
32    fn from(bounds: Bounds<ScaledPixels>) -> Self {
33        Self {
34            origin: [bounds.origin.x.0, bounds.origin.y.0],
35            size: [bounds.size.width.0, bounds.size.height.0],
36        }
37    }
38}
39
40#[repr(C)]
41#[derive(Clone, Copy, Pod, Zeroable)]
42struct SurfaceParams {
43    bounds: PodBounds,
44    content_mask: PodBounds,
45}
46
47#[repr(C)]
48#[derive(Clone, Copy, Pod, Zeroable)]
49struct GammaParams {
50    gamma_ratios: [f32; 4],
51    grayscale_enhanced_contrast: f32,
52    subpixel_enhanced_contrast: f32,
53    is_bgr: u32,
54    _pad: u32,
55}
56
57#[derive(Clone, Debug)]
58#[repr(C)]
59struct PathSprite {
60    bounds: Bounds<ScaledPixels>,
61}
62
63#[derive(Clone, Debug)]
64#[repr(C)]
65struct PathRasterizationVertex {
66    xy_position: Point<ScaledPixels>,
67    st_position: Point<f32>,
68    color: Background,
69    bounds: Bounds<ScaledPixels>,
70}
71
72pub struct WgpuSurfaceConfig {
73    pub size: Size<DevicePixels>,
74    pub transparent: bool,
75    /// Preferred presentation mode. When `Some`, the renderer will use this
76    /// mode if supported by the surface, falling back to `Fifo`.
77    /// When `None`, defaults to `Fifo` (VSync).
78    ///
79    /// Mobile platforms may prefer `Mailbox` (triple-buffering) to avoid
80    /// blocking in `get_current_texture()` during lifecycle transitions.
81    pub preferred_present_mode: Option<wgpu::PresentMode>,
82}
83
84struct WgpuPipelines {
85    quads: wgpu::RenderPipeline,
86    shadows: wgpu::RenderPipeline,
87    path_rasterization: wgpu::RenderPipeline,
88    paths: wgpu::RenderPipeline,
89    underlines: wgpu::RenderPipeline,
90    mono_sprites: wgpu::RenderPipeline,
91    subpixel_sprites: Option<wgpu::RenderPipeline>,
92    poly_sprites: wgpu::RenderPipeline,
93    #[allow(dead_code)]
94    surfaces: wgpu::RenderPipeline,
95}
96
97struct WgpuBindGroupLayouts {
98    globals: wgpu::BindGroupLayout,
99    instances: wgpu::BindGroupLayout,
100    instances_with_texture: wgpu::BindGroupLayout,
101    surfaces: wgpu::BindGroupLayout,
102}
103
104/// Shared GPU context reference, used to coordinate device recovery across multiple windows.
105pub type GpuContext = Rc<RefCell<Option<WgpuContext>>>;
106
107/// GPU resources that must be dropped together during device recovery.
108struct WgpuResources {
109    device: Arc<wgpu::Device>,
110    queue: Arc<wgpu::Queue>,
111    surface: wgpu::Surface<'static>,
112    pipelines: WgpuPipelines,
113    bind_group_layouts: WgpuBindGroupLayouts,
114    atlas_sampler: wgpu::Sampler,
115    globals_buffer: wgpu::Buffer,
116    globals_bind_group: wgpu::BindGroup,
117    path_globals_bind_group: wgpu::BindGroup,
118    instance_buffer: wgpu::Buffer,
119    path_intermediate_texture: Option<wgpu::Texture>,
120    path_intermediate_view: Option<wgpu::TextureView>,
121    path_msaa_texture: Option<wgpu::Texture>,
122    path_msaa_view: Option<wgpu::TextureView>,
123}
124
125impl WgpuResources {
126    fn invalidate_intermediate_textures(&mut self) {
127        self.path_intermediate_texture = None;
128        self.path_intermediate_view = None;
129        self.path_msaa_texture = None;
130        self.path_msaa_view = None;
131    }
132}
133
134pub struct WgpuRenderer {
135    /// Shared GPU context for device recovery coordination (unused on WASM).
136    #[allow(dead_code)]
137    context: Option<GpuContext>,
138    /// Compositor GPU hint for adapter selection (unused on WASM).
139    #[allow(dead_code)]
140    compositor_gpu: Option<CompositorGpuHint>,
141    resources: Option<WgpuResources>,
142    surface_config: wgpu::SurfaceConfiguration,
143    atlas: Arc<WgpuAtlas>,
144    path_globals_offset: u64,
145    gamma_offset: u64,
146    instance_buffer_capacity: u64,
147    max_buffer_size: u64,
148    storage_buffer_alignment: u64,
149    expanded_instance_binding_limit: Option<u64>,
150    rendering_params: RenderingParameters,
151    is_bgr: bool,
152    dual_source_blending: bool,
153    adapter_info: wgpu::AdapterInfo,
154    transparent_alpha_mode: wgpu::CompositeAlphaMode,
155    opaque_alpha_mode: wgpu::CompositeAlphaMode,
156    max_texture_size: u32,
157    last_error: Arc<Mutex<Option<String>>>,
158    failed_frame_count: u32,
159    device_lost: std::sync::Arc<std::sync::atomic::AtomicBool>,
160    surface_configured: bool,
161    needs_redraw: bool,
162}
163
164impl WgpuRenderer {
165    fn resources(&self) -> &WgpuResources {
166        self.resources
167            .as_ref()
168            .expect("GPU resources not available")
169    }
170
171    fn resources_mut(&mut self) -> &mut WgpuResources {
172        self.resources
173            .as_mut()
174            .expect("GPU resources not available")
175    }
176
177    /// Creates a new WgpuRenderer from raw window handles.
178    ///
179    /// The `gpu_context` is a shared reference that coordinates GPU context across
180    /// multiple windows. The first window to create a renderer will initialize the
181    /// context; subsequent windows will share it.
182    ///
183    /// # Safety
184    /// The caller must ensure that the window handle remains valid for the lifetime
185    /// of the returned renderer.
186    #[cfg(not(target_family = "wasm"))]
187    pub fn new<W>(
188        gpu_context: GpuContext,
189        window: &W,
190        config: WgpuSurfaceConfig,
191        compositor_gpu: Option<CompositorGpuHint>,
192    ) -> anyhow::Result<Self>
193    where
194        W: HasWindowHandle + HasDisplayHandle + std::fmt::Debug + Send + Sync + Clone + 'static,
195    {
196        let window_handle = window
197            .window_handle()
198            .map_err(|e| anyhow::anyhow!("Failed to get window handle: {e}"))?;
199
200        let target = wgpu::SurfaceTargetUnsafe::RawHandle {
201            // Fall back to the display handle already provided via InstanceDescriptor::display.
202            raw_display_handle: None,
203            raw_window_handle: window_handle.as_raw(),
204        };
205
206        // Use the existing context's instance if available, otherwise create a new one.
207        // The surface must be created with the same instance that will be used for
208        // adapter selection, otherwise wgpu will panic.
209        let instance = gpu_context
210            .borrow()
211            .as_ref()
212            .map(|ctx| ctx.instance.clone())
213            .unwrap_or_else(|| WgpuContext::instance(Box::new(window.clone())));
214
215        // Safety: The caller guarantees that the window handle is valid for the
216        // lifetime of this renderer. In practice, the RawWindow struct is created
217        // from the native window handles and the surface is dropped before the window.
218        let surface = unsafe {
219            instance
220                .create_surface_unsafe(target)
221                .map_err(|e| anyhow::anyhow!("Failed to create surface: {e}"))?
222        };
223
224        let mut ctx_ref = gpu_context.borrow_mut();
225        let context = match ctx_ref.as_mut() {
226            Some(context) => {
227                context.check_compatible_with_surface(&surface)?;
228                context
229            }
230            None => ctx_ref.insert(WgpuContext::new(instance, &surface, compositor_gpu)?),
231        };
232
233        let atlas = Arc::new(WgpuAtlas::from_context(context));
234
235        Self::new_internal(
236            Some(Rc::clone(&gpu_context)),
237            context,
238            surface,
239            config,
240            compositor_gpu,
241            atlas,
242        )
243    }
244
245    #[cfg(target_family = "wasm")]
246    pub fn new_from_canvas(
247        context: &WgpuContext,
248        canvas: &web_sys::HtmlCanvasElement,
249        config: WgpuSurfaceConfig,
250    ) -> anyhow::Result<Self> {
251        let surface = context
252            .instance
253            .create_surface(wgpu::SurfaceTarget::Canvas(canvas.clone()))
254            .map_err(|e| anyhow::anyhow!("Failed to create surface: {e}"))?;
255
256        let atlas = Arc::new(WgpuAtlas::from_context(context));
257
258        Self::new_internal(None, context, surface, config, None, atlas)
259    }
260
261    fn new_internal(
262        gpu_context: Option<GpuContext>,
263        context: &WgpuContext,
264        surface: wgpu::Surface<'static>,
265        config: WgpuSurfaceConfig,
266        compositor_gpu: Option<CompositorGpuHint>,
267        atlas: Arc<WgpuAtlas>,
268    ) -> anyhow::Result<Self> {
269        let surface_caps = surface.get_capabilities(&context.adapter);
270        let preferred_formats = [
271            wgpu::TextureFormat::Bgra8Unorm,
272            wgpu::TextureFormat::Rgba8Unorm,
273        ];
274        let surface_format = preferred_formats
275            .iter()
276            .find(|f| surface_caps.formats.contains(f))
277            .copied()
278            .or_else(|| surface_caps.formats.iter().find(|f| !f.is_srgb()).copied())
279            .or_else(|| surface_caps.formats.first().copied())
280            .ok_or_else(|| {
281                anyhow::anyhow!(
282                    "Surface reports no supported texture formats for adapter {:?}",
283                    context.adapter.get_info().name
284                )
285            })?;
286
287        let pick_alpha_mode =
288            |preferences: &[wgpu::CompositeAlphaMode]| -> anyhow::Result<wgpu::CompositeAlphaMode> {
289                preferences
290                    .iter()
291                    .find(|p| surface_caps.alpha_modes.contains(p))
292                    .copied()
293                    .or_else(|| surface_caps.alpha_modes.first().copied())
294                    .ok_or_else(|| {
295                        anyhow::anyhow!(
296                            "Surface reports no supported alpha modes for adapter {:?}",
297                            context.adapter.get_info().name
298                        )
299                    })
300            };
301
302        let transparent_alpha_mode = pick_alpha_mode(&[
303            wgpu::CompositeAlphaMode::PreMultiplied,
304            wgpu::CompositeAlphaMode::Inherit,
305        ])?;
306
307        let opaque_alpha_mode = pick_alpha_mode(&[
308            wgpu::CompositeAlphaMode::Opaque,
309            wgpu::CompositeAlphaMode::Inherit,
310        ])?;
311
312        let alpha_mode = if config.transparent {
313            transparent_alpha_mode
314        } else {
315            opaque_alpha_mode
316        };
317
318        let device = Arc::clone(&context.device);
319        let max_texture_size = device.limits().max_texture_dimension_2d;
320
321        let requested_width = config.size.width.0 as u32;
322        let requested_height = config.size.height.0 as u32;
323        let clamped_width = requested_width.min(max_texture_size);
324        let clamped_height = requested_height.min(max_texture_size);
325
326        if clamped_width != requested_width || clamped_height != requested_height {
327            warn!(
328                "Requested surface size ({}, {}) exceeds maximum texture dimension {}. \
329                 Clamping to ({}, {}). Window content may not fill the entire window.",
330                requested_width, requested_height, max_texture_size, clamped_width, clamped_height
331            );
332        }
333
334        let surface_config = wgpu::SurfaceConfiguration {
335            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
336            format: surface_format,
337            width: clamped_width.max(1),
338            height: clamped_height.max(1),
339            present_mode: config
340                .preferred_present_mode
341                .filter(|mode| surface_caps.present_modes.contains(mode))
342                .unwrap_or(wgpu::PresentMode::Fifo),
343            desired_maximum_frame_latency: 2,
344            alpha_mode,
345            view_formats: vec![],
346        };
347        // Configure the surface immediately. The adapter selection process already validated
348        // that this adapter can successfully configure this surface.
349        surface.configure(&context.device, &surface_config);
350
351        let queue = Arc::clone(&context.queue);
352        let dual_source_blending = context.supports_dual_source_blending();
353
354        let rendering_params = RenderingParameters::new(&context.adapter, surface_format);
355        let bind_group_layouts = Self::create_bind_group_layouts(&device);
356        let pipelines = Self::create_pipelines(
357            &device,
358            &bind_group_layouts,
359            surface_format,
360            alpha_mode,
361            rendering_params.path_sample_count,
362            dual_source_blending,
363        );
364
365        let atlas_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
366            label: Some("atlas_sampler"),
367            mag_filter: wgpu::FilterMode::Linear,
368            min_filter: wgpu::FilterMode::Linear,
369            ..Default::default()
370        });
371
372        let uniform_alignment = device.limits().min_uniform_buffer_offset_alignment as u64;
373        let globals_size = std::mem::size_of::<GlobalParams>() as u64;
374        let gamma_size = std::mem::size_of::<GammaParams>() as u64;
375        let path_globals_offset = globals_size.next_multiple_of(uniform_alignment);
376        let gamma_offset = (path_globals_offset + globals_size).next_multiple_of(uniform_alignment);
377
378        let globals_buffer = device.create_buffer(&wgpu::BufferDescriptor {
379            label: Some("globals_buffer"),
380            size: gamma_offset + gamma_size,
381            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
382            mapped_at_creation: false,
383        });
384
385        let adapter_info = context.adapter.get_info();
386        let max_buffer_size = device.limits().max_buffer_size;
387        let storage_buffer_alignment = device.limits().min_storage_buffer_offset_alignment as u64;
388        let expanded_instance_binding_limit = (adapter_info.backend == wgpu::Backend::Gl
389            && adapter_info.name.starts_with("SVGA3D"))
390        .then_some(device.limits().max_storage_buffer_binding_size);
391        let initial_instance_buffer_capacity = 2 * 1024 * 1024;
392        let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
393            label: Some("instance_buffer"),
394            size: initial_instance_buffer_capacity,
395            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
396            mapped_at_creation: false,
397        });
398
399        let globals_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
400            label: Some("globals_bind_group"),
401            layout: &bind_group_layouts.globals,
402            entries: &[
403                wgpu::BindGroupEntry {
404                    binding: 0,
405                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
406                        buffer: &globals_buffer,
407                        offset: 0,
408                        size: Some(NonZeroU64::new(globals_size).unwrap()),
409                    }),
410                },
411                wgpu::BindGroupEntry {
412                    binding: 1,
413                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
414                        buffer: &globals_buffer,
415                        offset: gamma_offset,
416                        size: Some(NonZeroU64::new(gamma_size).unwrap()),
417                    }),
418                },
419            ],
420        });
421
422        let path_globals_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
423            label: Some("path_globals_bind_group"),
424            layout: &bind_group_layouts.globals,
425            entries: &[
426                wgpu::BindGroupEntry {
427                    binding: 0,
428                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
429                        buffer: &globals_buffer,
430                        offset: path_globals_offset,
431                        size: Some(NonZeroU64::new(globals_size).unwrap()),
432                    }),
433                },
434                wgpu::BindGroupEntry {
435                    binding: 1,
436                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
437                        buffer: &globals_buffer,
438                        offset: gamma_offset,
439                        size: Some(NonZeroU64::new(gamma_size).unwrap()),
440                    }),
441                },
442            ],
443        });
444
445        let last_error: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
446        let last_error_clone = Arc::clone(&last_error);
447        device.on_uncaptured_error(Arc::new(move |error| {
448            let mut guard = last_error_clone.lock().unwrap();
449            *guard = Some(error.to_string());
450        }));
451
452        let resources = WgpuResources {
453            device,
454            queue,
455            surface,
456            pipelines,
457            bind_group_layouts,
458            atlas_sampler,
459            globals_buffer,
460            globals_bind_group,
461            path_globals_bind_group,
462            instance_buffer,
463            // Defer intermediate texture creation to first draw call via ensure_intermediate_textures().
464            // This avoids panics when the device/surface is in an invalid state during initialization.
465            path_intermediate_texture: None,
466            path_intermediate_view: None,
467            path_msaa_texture: None,
468            path_msaa_view: None,
469        };
470
471        Ok(Self {
472            context: gpu_context,
473            compositor_gpu,
474            resources: Some(resources),
475            surface_config,
476            atlas,
477            path_globals_offset,
478            gamma_offset,
479            instance_buffer_capacity: initial_instance_buffer_capacity,
480            max_buffer_size,
481            storage_buffer_alignment,
482            expanded_instance_binding_limit,
483            rendering_params,
484            is_bgr: false,
485            dual_source_blending,
486            adapter_info,
487            transparent_alpha_mode,
488            opaque_alpha_mode,
489            max_texture_size,
490            last_error,
491            failed_frame_count: 0,
492            device_lost: context.device_lost_flag(),
493            surface_configured: true,
494            needs_redraw: false,
495        })
496    }
497
498    fn create_bind_group_layouts(device: &wgpu::Device) -> WgpuBindGroupLayouts {
499        let globals =
500            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
501                label: Some("globals_layout"),
502                entries: &[
503                    wgpu::BindGroupLayoutEntry {
504                        binding: 0,
505                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
506                        ty: wgpu::BindingType::Buffer {
507                            ty: wgpu::BufferBindingType::Uniform,
508                            has_dynamic_offset: false,
509                            min_binding_size: NonZeroU64::new(
510                                std::mem::size_of::<GlobalParams>() as u64
511                            ),
512                        },
513                        count: None,
514                    },
515                    wgpu::BindGroupLayoutEntry {
516                        binding: 1,
517                        visibility: wgpu::ShaderStages::FRAGMENT,
518                        ty: wgpu::BindingType::Buffer {
519                            ty: wgpu::BufferBindingType::Uniform,
520                            has_dynamic_offset: false,
521                            min_binding_size: NonZeroU64::new(
522                                std::mem::size_of::<GammaParams>() as u64
523                            ),
524                        },
525                        count: None,
526                    },
527                ],
528            });
529
530        let storage_buffer_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
531            binding,
532            visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
533            ty: wgpu::BindingType::Buffer {
534                ty: wgpu::BufferBindingType::Storage { read_only: true },
535                has_dynamic_offset: false,
536                min_binding_size: None,
537            },
538            count: None,
539        };
540
541        let instances = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
542            label: Some("instances_layout"),
543            entries: &[storage_buffer_entry(0)],
544        });
545
546        let instances_with_texture =
547            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
548                label: Some("instances_with_texture_layout"),
549                entries: &[
550                    storage_buffer_entry(0),
551                    wgpu::BindGroupLayoutEntry {
552                        binding: 1,
553                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
554                        ty: wgpu::BindingType::Texture {
555                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
556                            view_dimension: wgpu::TextureViewDimension::D2,
557                            multisampled: false,
558                        },
559                        count: None,
560                    },
561                    wgpu::BindGroupLayoutEntry {
562                        binding: 2,
563                        visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
564                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
565                        count: None,
566                    },
567                ],
568            });
569
570        let surfaces = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
571            label: Some("surfaces_layout"),
572            entries: &[
573                wgpu::BindGroupLayoutEntry {
574                    binding: 0,
575                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
576                    ty: wgpu::BindingType::Buffer {
577                        ty: wgpu::BufferBindingType::Uniform,
578                        has_dynamic_offset: false,
579                        min_binding_size: NonZeroU64::new(
580                            std::mem::size_of::<SurfaceParams>() as u64
581                        ),
582                    },
583                    count: None,
584                },
585                wgpu::BindGroupLayoutEntry {
586                    binding: 1,
587                    visibility: wgpu::ShaderStages::FRAGMENT,
588                    ty: wgpu::BindingType::Texture {
589                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
590                        view_dimension: wgpu::TextureViewDimension::D2,
591                        multisampled: false,
592                    },
593                    count: None,
594                },
595                wgpu::BindGroupLayoutEntry {
596                    binding: 2,
597                    visibility: wgpu::ShaderStages::FRAGMENT,
598                    ty: wgpu::BindingType::Texture {
599                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
600                        view_dimension: wgpu::TextureViewDimension::D2,
601                        multisampled: false,
602                    },
603                    count: None,
604                },
605                wgpu::BindGroupLayoutEntry {
606                    binding: 3,
607                    visibility: wgpu::ShaderStages::FRAGMENT,
608                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
609                    count: None,
610                },
611            ],
612        });
613
614        WgpuBindGroupLayouts {
615            globals,
616            instances,
617            instances_with_texture,
618            surfaces,
619        }
620    }
621
622    fn create_pipelines(
623        device: &wgpu::Device,
624        layouts: &WgpuBindGroupLayouts,
625        surface_format: wgpu::TextureFormat,
626        alpha_mode: wgpu::CompositeAlphaMode,
627        path_sample_count: u32,
628        dual_source_blending: bool,
629    ) -> WgpuPipelines {
630        // Diagnostic guard: verify the device actually has
631        // DUAL_SOURCE_BLENDING. We have a crash report (ZED-5G1) where a
632        // feature mismatch caused a wgpu-hal abort, but we haven't
633        // identified the code path that produces the mismatch. This
634        // guard prevents the crash and logs more evidence.
635        // Remove this check once:
636        // a) We find and fix the root cause, or
637        // b) There are no reports of this warning appearing for some time.
638        let device_has_feature = device
639            .features()
640            .contains(wgpu::Features::DUAL_SOURCE_BLENDING);
641        if dual_source_blending && !device_has_feature {
642            log::error!(
643                "BUG: dual_source_blending flag is true but device does not \
644                 have DUAL_SOURCE_BLENDING enabled (device features: {:?}). \
645                 Falling back to mono text rendering. Please report this at \
646                 https://github.com/zed-industries/zed/issues",
647                device.features(),
648            );
649        }
650        let dual_source_blending = dual_source_blending && device_has_feature;
651
652        let base_shader_source = include_str!("shaders.wgsl");
653        let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
654            label: Some("gpui_shaders"),
655            source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(base_shader_source)),
656        });
657
658        let subpixel_shader_source = include_str!("shaders_subpixel.wgsl");
659        let subpixel_shader_module = if dual_source_blending {
660            let combined = format!(
661                "enable dual_source_blending;\n{base_shader_source}\n{subpixel_shader_source}"
662            );
663            Some(device.create_shader_module(wgpu::ShaderModuleDescriptor {
664                label: Some("gpui_subpixel_shaders"),
665                source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Owned(combined)),
666            }))
667        } else {
668            None
669        };
670
671        let blend_mode = match alpha_mode {
672            wgpu::CompositeAlphaMode::PreMultiplied => {
673                wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING
674            }
675            _ => wgpu::BlendState::ALPHA_BLENDING,
676        };
677
678        let color_target = wgpu::ColorTargetState {
679            format: surface_format,
680            blend: Some(blend_mode),
681            write_mask: wgpu::ColorWrites::ALL,
682        };
683
684        let create_pipeline = |name: &str,
685                               vs_entry: &str,
686                               fs_entry: &str,
687                               globals_layout: &wgpu::BindGroupLayout,
688                               data_layout: &wgpu::BindGroupLayout,
689                               topology: wgpu::PrimitiveTopology,
690                               color_targets: &[Option<wgpu::ColorTargetState>],
691                               sample_count: u32,
692                               module: &wgpu::ShaderModule| {
693            let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
694                label: Some(&format!("{name}_layout")),
695                bind_group_layouts: &[Some(globals_layout), Some(data_layout)],
696                immediate_size: 0,
697            });
698
699            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
700                label: Some(name),
701                layout: Some(&pipeline_layout),
702                vertex: wgpu::VertexState {
703                    module,
704                    entry_point: Some(vs_entry),
705                    buffers: &[],
706                    compilation_options: wgpu::PipelineCompilationOptions::default(),
707                },
708                fragment: Some(wgpu::FragmentState {
709                    module,
710                    entry_point: Some(fs_entry),
711                    targets: color_targets,
712                    compilation_options: wgpu::PipelineCompilationOptions::default(),
713                }),
714                primitive: wgpu::PrimitiveState {
715                    topology,
716                    strip_index_format: None,
717                    front_face: wgpu::FrontFace::Ccw,
718                    cull_mode: None,
719                    polygon_mode: wgpu::PolygonMode::Fill,
720                    unclipped_depth: false,
721                    conservative: false,
722                },
723                depth_stencil: None,
724                multisample: wgpu::MultisampleState {
725                    count: sample_count,
726                    mask: !0,
727                    alpha_to_coverage_enabled: false,
728                },
729                multiview_mask: None,
730                cache: None,
731            })
732        };
733
734        let quads = create_pipeline(
735            "quads",
736            "vs_quad",
737            "fs_quad",
738            &layouts.globals,
739            &layouts.instances,
740            wgpu::PrimitiveTopology::TriangleStrip,
741            &[Some(color_target.clone())],
742            1,
743            &shader_module,
744        );
745
746        let shadows = create_pipeline(
747            "shadows",
748            "vs_shadow",
749            "fs_shadow",
750            &layouts.globals,
751            &layouts.instances,
752            wgpu::PrimitiveTopology::TriangleStrip,
753            &[Some(color_target.clone())],
754            1,
755            &shader_module,
756        );
757
758        let path_rasterization = create_pipeline(
759            "path_rasterization",
760            "vs_path_rasterization",
761            "fs_path_rasterization",
762            &layouts.globals,
763            &layouts.instances,
764            wgpu::PrimitiveTopology::TriangleList,
765            &[Some(wgpu::ColorTargetState {
766                format: surface_format,
767                blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
768                write_mask: wgpu::ColorWrites::ALL,
769            })],
770            path_sample_count,
771            &shader_module,
772        );
773
774        let paths_blend = wgpu::BlendState {
775            color: wgpu::BlendComponent {
776                src_factor: wgpu::BlendFactor::One,
777                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
778                operation: wgpu::BlendOperation::Add,
779            },
780            alpha: wgpu::BlendComponent {
781                src_factor: wgpu::BlendFactor::One,
782                dst_factor: wgpu::BlendFactor::One,
783                operation: wgpu::BlendOperation::Add,
784            },
785        };
786
787        let paths = create_pipeline(
788            "paths",
789            "vs_path",
790            "fs_path",
791            &layouts.globals,
792            &layouts.instances_with_texture,
793            wgpu::PrimitiveTopology::TriangleStrip,
794            &[Some(wgpu::ColorTargetState {
795                format: surface_format,
796                blend: Some(paths_blend),
797                write_mask: wgpu::ColorWrites::ALL,
798            })],
799            1,
800            &shader_module,
801        );
802
803        let underlines = create_pipeline(
804            "underlines",
805            "vs_underline",
806            "fs_underline",
807            &layouts.globals,
808            &layouts.instances,
809            wgpu::PrimitiveTopology::TriangleStrip,
810            &[Some(color_target.clone())],
811            1,
812            &shader_module,
813        );
814
815        let mono_sprites = create_pipeline(
816            "mono_sprites",
817            "vs_mono_sprite",
818            "fs_mono_sprite",
819            &layouts.globals,
820            &layouts.instances_with_texture,
821            wgpu::PrimitiveTopology::TriangleStrip,
822            &[Some(color_target.clone())],
823            1,
824            &shader_module,
825        );
826
827        let subpixel_sprites = if let Some(subpixel_module) = &subpixel_shader_module {
828            let subpixel_blend = wgpu::BlendState {
829                color: wgpu::BlendComponent {
830                    src_factor: wgpu::BlendFactor::Src1,
831                    dst_factor: wgpu::BlendFactor::OneMinusSrc1,
832                    operation: wgpu::BlendOperation::Add,
833                },
834                alpha: wgpu::BlendComponent {
835                    src_factor: wgpu::BlendFactor::One,
836                    dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
837                    operation: wgpu::BlendOperation::Add,
838                },
839            };
840
841            Some(create_pipeline(
842                "subpixel_sprites",
843                "vs_subpixel_sprite",
844                "fs_subpixel_sprite",
845                &layouts.globals,
846                &layouts.instances_with_texture,
847                wgpu::PrimitiveTopology::TriangleStrip,
848                &[Some(wgpu::ColorTargetState {
849                    format: surface_format,
850                    blend: Some(subpixel_blend),
851                    write_mask: wgpu::ColorWrites::COLOR,
852                })],
853                1,
854                subpixel_module,
855            ))
856        } else {
857            None
858        };
859
860        let poly_sprites = create_pipeline(
861            "poly_sprites",
862            "vs_poly_sprite",
863            "fs_poly_sprite",
864            &layouts.globals,
865            &layouts.instances_with_texture,
866            wgpu::PrimitiveTopology::TriangleStrip,
867            &[Some(color_target.clone())],
868            1,
869            &shader_module,
870        );
871
872        let surfaces = create_pipeline(
873            "surfaces",
874            "vs_surface",
875            "fs_surface",
876            &layouts.globals,
877            &layouts.surfaces,
878            wgpu::PrimitiveTopology::TriangleStrip,
879            &[Some(color_target)],
880            1,
881            &shader_module,
882        );
883
884        WgpuPipelines {
885            quads,
886            shadows,
887            path_rasterization,
888            paths,
889            underlines,
890            mono_sprites,
891            subpixel_sprites,
892            poly_sprites,
893            surfaces,
894        }
895    }
896
897    fn create_path_intermediate(
898        device: &wgpu::Device,
899        format: wgpu::TextureFormat,
900        width: u32,
901        height: u32,
902    ) -> (wgpu::Texture, wgpu::TextureView) {
903        let texture = device.create_texture(&wgpu::TextureDescriptor {
904            label: Some("path_intermediate"),
905            size: wgpu::Extent3d {
906                width: width.max(1),
907                height: height.max(1),
908                depth_or_array_layers: 1,
909            },
910            mip_level_count: 1,
911            sample_count: 1,
912            dimension: wgpu::TextureDimension::D2,
913            format,
914            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
915            view_formats: &[],
916        });
917        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
918        (texture, view)
919    }
920
921    fn create_msaa_if_needed(
922        device: &wgpu::Device,
923        format: wgpu::TextureFormat,
924        width: u32,
925        height: u32,
926        sample_count: u32,
927    ) -> Option<(wgpu::Texture, wgpu::TextureView)> {
928        if sample_count <= 1 {
929            return None;
930        }
931        let texture = device.create_texture(&wgpu::TextureDescriptor {
932            label: Some("path_msaa"),
933            size: wgpu::Extent3d {
934                width: width.max(1),
935                height: height.max(1),
936                depth_or_array_layers: 1,
937            },
938            mip_level_count: 1,
939            sample_count,
940            dimension: wgpu::TextureDimension::D2,
941            format,
942            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
943            view_formats: &[],
944        });
945        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
946        Some((texture, view))
947    }
948
949    pub fn update_drawable_size(&mut self, size: Size<DevicePixels>) {
950        let width = size.width.0 as u32;
951        let height = size.height.0 as u32;
952
953        if width != self.surface_config.width || height != self.surface_config.height {
954            let clamped_width = width.min(self.max_texture_size);
955            let clamped_height = height.min(self.max_texture_size);
956
957            if clamped_width != width || clamped_height != height {
958                warn!(
959                    "Requested surface size ({}, {}) exceeds maximum texture dimension {}. \
960                     Clamping to ({}, {}). Window content may not fill the entire window.",
961                    width, height, self.max_texture_size, clamped_width, clamped_height
962                );
963            }
964
965            self.surface_config.width = clamped_width.max(1);
966            self.surface_config.height = clamped_height.max(1);
967            let surface_config = self.surface_config.clone();
968
969            let Some(resources) = self.resources.as_mut() else {
970                return;
971            };
972
973            // Wait for any in-flight GPU work to complete before destroying textures
974            if let Err(e) = resources.device.poll(wgpu::PollType::Wait {
975                submission_index: None,
976                timeout: None,
977            }) {
978                warn!("Failed to poll device during resize: {e:?}");
979            }
980
981            // Destroy old textures before allocating new ones to avoid GPU memory spikes
982            if let Some(ref texture) = resources.path_intermediate_texture {
983                texture.destroy();
984            }
985            if let Some(ref texture) = resources.path_msaa_texture {
986                texture.destroy();
987            }
988
989            resources
990                .surface
991                .configure(&resources.device, &surface_config);
992
993            // Invalidate intermediate textures - they will be lazily recreated
994            // in draw() after we confirm the surface is healthy. This avoids
995            // panics when the device/surface is in an invalid state during resize.
996            resources.invalidate_intermediate_textures();
997        }
998    }
999
1000    fn ensure_intermediate_textures(&mut self) {
1001        if self.resources().path_intermediate_texture.is_some() {
1002            return;
1003        }
1004
1005        let format = self.surface_config.format;
1006        let width = self.surface_config.width;
1007        let height = self.surface_config.height;
1008        let path_sample_count = self.rendering_params.path_sample_count;
1009        let resources = self.resources_mut();
1010
1011        let (t, v) = Self::create_path_intermediate(&resources.device, format, width, height);
1012        resources.path_intermediate_texture = Some(t);
1013        resources.path_intermediate_view = Some(v);
1014
1015        let (path_msaa_texture, path_msaa_view) = Self::create_msaa_if_needed(
1016            &resources.device,
1017            format,
1018            width,
1019            height,
1020            path_sample_count,
1021        )
1022        .map(|(t, v)| (Some(t), Some(v)))
1023        .unwrap_or((None, None));
1024        resources.path_msaa_texture = path_msaa_texture;
1025        resources.path_msaa_view = path_msaa_view;
1026    }
1027
1028    pub fn set_subpixel_layout(&mut self, is_bgr: bool) {
1029        self.is_bgr = is_bgr;
1030    }
1031
1032    pub fn update_transparency(&mut self, transparent: bool) {
1033        let new_alpha_mode = if transparent {
1034            self.transparent_alpha_mode
1035        } else {
1036            self.opaque_alpha_mode
1037        };
1038
1039        if new_alpha_mode != self.surface_config.alpha_mode {
1040            self.surface_config.alpha_mode = new_alpha_mode;
1041            let surface_config = self.surface_config.clone();
1042            let path_sample_count = self.rendering_params.path_sample_count;
1043            let dual_source_blending = self.dual_source_blending;
1044            let Some(resources) = self.resources.as_mut() else {
1045                return;
1046            };
1047            resources
1048                .surface
1049                .configure(&resources.device, &surface_config);
1050            resources.pipelines = Self::create_pipelines(
1051                &resources.device,
1052                &resources.bind_group_layouts,
1053                surface_config.format,
1054                surface_config.alpha_mode,
1055                path_sample_count,
1056                dual_source_blending,
1057            );
1058        }
1059    }
1060
1061    #[allow(dead_code)]
1062    pub fn viewport_size(&self) -> Size<DevicePixels> {
1063        Size {
1064            width: DevicePixels(self.surface_config.width as i32),
1065            height: DevicePixels(self.surface_config.height as i32),
1066        }
1067    }
1068
1069    pub fn sprite_atlas(&self) -> &Arc<WgpuAtlas> {
1070        &self.atlas
1071    }
1072
1073    pub fn supports_dual_source_blending(&self) -> bool {
1074        self.dual_source_blending
1075    }
1076
1077    pub fn gpu_specs(&self) -> GpuSpecs {
1078        GpuSpecs {
1079            is_software_emulated: self.adapter_info.device_type == wgpu::DeviceType::Cpu,
1080            device_name: self.adapter_info.name.clone(),
1081            driver_name: self.adapter_info.driver.clone(),
1082            driver_info: self.adapter_info.driver_info.clone(),
1083        }
1084    }
1085
1086    pub fn max_texture_size(&self) -> u32 {
1087        self.max_texture_size
1088    }
1089
1090    pub fn draw(&mut self, scene: &Scene) -> bool {
1091        // Bail out early if the surface has been unconfigured (e.g. during
1092        // Android background/rotation transitions).  Attempting to acquire
1093        // a texture from an unconfigured surface can block indefinitely on
1094        // some drivers (Adreno).
1095        if !self.surface_configured {
1096            return false;
1097        }
1098
1099        let last_error = self.last_error.lock().unwrap().take();
1100        if let Some(error) = last_error {
1101            self.failed_frame_count += 1;
1102            log::error!(
1103                "GPU error during frame (failure {} of 10): {error}",
1104                self.failed_frame_count
1105            );
1106
1107            // TBD. Does retrying more actually help?
1108            if self.failed_frame_count > 10 {
1109                panic!("Too many consecutive GPU errors. Last error: {error}");
1110            } else if self.failed_frame_count > 5 {
1111                if let Some(res) = self.resources.as_mut() {
1112                    res.invalidate_intermediate_textures();
1113                }
1114                self.atlas.clear();
1115                self.needs_redraw = true;
1116                self.failed_frame_count = 0;
1117                return false;
1118            }
1119        } else {
1120            self.failed_frame_count = 0;
1121        }
1122
1123        self.atlas.before_frame();
1124
1125        let frame = match self.resources().surface.get_current_texture() {
1126            wgpu::CurrentSurfaceTexture::Success(frame) => frame,
1127            wgpu::CurrentSurfaceTexture::Suboptimal(frame) => {
1128                // Textures must be destroyed before the surface can be reconfigured.
1129                drop(frame);
1130                let surface_config = self.surface_config.clone();
1131                let resources = self.resources_mut();
1132                resources
1133                    .surface
1134                    .configure(&resources.device, &surface_config);
1135                return false;
1136            }
1137            wgpu::CurrentSurfaceTexture::Lost | wgpu::CurrentSurfaceTexture::Outdated => {
1138                let surface_config = self.surface_config.clone();
1139                let resources = self.resources_mut();
1140                resources
1141                    .surface
1142                    .configure(&resources.device, &surface_config);
1143                return false;
1144            }
1145            wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
1146                return false;
1147            }
1148            wgpu::CurrentSurfaceTexture::Validation => {
1149                *self.last_error.lock().unwrap() =
1150                    Some("Surface texture validation error".to_string());
1151                return false;
1152            }
1153        };
1154
1155        // Now that we know the surface is healthy, ensure intermediate textures exist
1156        self.ensure_intermediate_textures();
1157
1158        let frame_view = frame
1159            .texture
1160            .create_view(&wgpu::TextureViewDescriptor::default());
1161
1162        let gamma_params = GammaParams {
1163            gamma_ratios: self.rendering_params.gamma_ratios,
1164            grayscale_enhanced_contrast: self.rendering_params.grayscale_enhanced_contrast,
1165            subpixel_enhanced_contrast: self.rendering_params.subpixel_enhanced_contrast,
1166            is_bgr: self.is_bgr as u32,
1167            _pad: 0,
1168        };
1169
1170        let globals = GlobalParams {
1171            viewport_size: [
1172                self.surface_config.width as f32,
1173                self.surface_config.height as f32,
1174            ],
1175            premultiplied_alpha: if self.surface_config.alpha_mode
1176                == wgpu::CompositeAlphaMode::PreMultiplied
1177            {
1178                1
1179            } else {
1180                0
1181            },
1182            pad: 0,
1183        };
1184
1185        let path_globals = GlobalParams {
1186            premultiplied_alpha: 0,
1187            ..globals
1188        };
1189
1190        {
1191            let resources = self.resources();
1192            resources.queue.write_buffer(
1193                &resources.globals_buffer,
1194                0,
1195                bytemuck::bytes_of(&globals),
1196            );
1197            resources.queue.write_buffer(
1198                &resources.globals_buffer,
1199                self.path_globals_offset,
1200                bytemuck::bytes_of(&path_globals),
1201            );
1202            resources.queue.write_buffer(
1203                &resources.globals_buffer,
1204                self.gamma_offset,
1205                bytemuck::bytes_of(&gamma_params),
1206            );
1207        }
1208
1209        loop {
1210            let mut instance_offset: u64 = 0;
1211            let mut overflow = false;
1212
1213            let mut encoder =
1214                self.resources()
1215                    .device
1216                    .create_command_encoder(&wgpu::CommandEncoderDescriptor {
1217                        label: Some("main_encoder"),
1218                    });
1219
1220            {
1221                let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1222                    label: Some("main_pass"),
1223                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1224                        view: &frame_view,
1225                        resolve_target: None,
1226                        ops: wgpu::Operations {
1227                            load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
1228                            store: wgpu::StoreOp::Store,
1229                        },
1230                        depth_slice: None,
1231                    })],
1232                    depth_stencil_attachment: None,
1233                    ..Default::default()
1234                });
1235
1236                for batch in scene.batches() {
1237                    let ok = match batch {
1238                        PrimitiveBatch::Quads(range) => {
1239                            self.draw_quads(&scene.quads[range], &mut instance_offset, &mut pass)
1240                        }
1241                        PrimitiveBatch::Shadows(range) => self.draw_shadows(
1242                            &scene.shadows[range],
1243                            &mut instance_offset,
1244                            &mut pass,
1245                        ),
1246                        PrimitiveBatch::Paths(range) => {
1247                            let paths = &scene.paths[range];
1248                            if paths.is_empty() {
1249                                continue;
1250                            }
1251
1252                            drop(pass);
1253
1254                            let did_draw = self.draw_paths_to_intermediate(
1255                                &mut encoder,
1256                                paths,
1257                                &mut instance_offset,
1258                            );
1259
1260                            pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1261                                label: Some("main_pass_continued"),
1262                                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1263                                    view: &frame_view,
1264                                    resolve_target: None,
1265                                    ops: wgpu::Operations {
1266                                        load: wgpu::LoadOp::Load,
1267                                        store: wgpu::StoreOp::Store,
1268                                    },
1269                                    depth_slice: None,
1270                                })],
1271                                depth_stencil_attachment: None,
1272                                ..Default::default()
1273                            });
1274
1275                            if did_draw {
1276                                self.draw_paths_from_intermediate(
1277                                    paths,
1278                                    &mut instance_offset,
1279                                    &mut pass,
1280                                )
1281                            } else {
1282                                false
1283                            }
1284                        }
1285                        PrimitiveBatch::Underlines(range) => self.draw_underlines(
1286                            &scene.underlines[range],
1287                            &mut instance_offset,
1288                            &mut pass,
1289                        ),
1290                        PrimitiveBatch::MonochromeSprites { texture_id, range } => self
1291                            .draw_monochrome_sprites(
1292                                &scene.monochrome_sprites[range],
1293                                texture_id,
1294                                &mut instance_offset,
1295                                &mut pass,
1296                            ),
1297                        PrimitiveBatch::SubpixelSprites { texture_id, range } => self
1298                            .draw_subpixel_sprites(
1299                                &scene.subpixel_sprites[range],
1300                                texture_id,
1301                                &mut instance_offset,
1302                                &mut pass,
1303                            ),
1304                        PrimitiveBatch::PolychromeSprites { texture_id, range } => self
1305                            .draw_polychrome_sprites(
1306                                &scene.polychrome_sprites[range],
1307                                texture_id,
1308                                &mut instance_offset,
1309                                &mut pass,
1310                            ),
1311                        PrimitiveBatch::Surfaces(_surfaces) => {
1312                            // Surfaces are macOS-only for video playback
1313                            // Not implemented for Linux/wgpu
1314                            true
1315                        }
1316                    };
1317                    if !ok {
1318                        overflow = true;
1319                        break;
1320                    }
1321                }
1322            }
1323
1324            if overflow {
1325                drop(encoder);
1326                if self.instance_buffer_capacity >= self.max_buffer_size {
1327                    log::error!(
1328                        "instance buffer size grew too large: {}",
1329                        self.instance_buffer_capacity
1330                    );
1331                    frame.present();
1332                    return true;
1333                }
1334                self.grow_instance_buffer();
1335                continue;
1336            }
1337
1338            self.resources()
1339                .queue
1340                .submit(std::iter::once(encoder.finish()));
1341            frame.present();
1342            return true;
1343        }
1344    }
1345
1346    fn draw_quads(
1347        &self,
1348        quads: &[Quad],
1349        instance_offset: &mut u64,
1350        pass: &mut wgpu::RenderPass<'_>,
1351    ) -> bool {
1352        let data = unsafe { Self::instance_bytes(quads) };
1353        self.draw_instances(
1354            data,
1355            quads.len() as u32,
1356            &self.resources().pipelines.quads,
1357            instance_offset,
1358            pass,
1359        )
1360    }
1361
1362    fn draw_shadows(
1363        &self,
1364        shadows: &[Shadow],
1365        instance_offset: &mut u64,
1366        pass: &mut wgpu::RenderPass<'_>,
1367    ) -> bool {
1368        let data = unsafe { Self::instance_bytes(shadows) };
1369        self.draw_instances(
1370            data,
1371            shadows.len() as u32,
1372            &self.resources().pipelines.shadows,
1373            instance_offset,
1374            pass,
1375        )
1376    }
1377
1378    fn draw_underlines(
1379        &self,
1380        underlines: &[Underline],
1381        instance_offset: &mut u64,
1382        pass: &mut wgpu::RenderPass<'_>,
1383    ) -> bool {
1384        let data = unsafe { Self::instance_bytes(underlines) };
1385        self.draw_instances(
1386            data,
1387            underlines.len() as u32,
1388            &self.resources().pipelines.underlines,
1389            instance_offset,
1390            pass,
1391        )
1392    }
1393
1394    fn draw_monochrome_sprites(
1395        &self,
1396        sprites: &[MonochromeSprite],
1397        texture_id: AtlasTextureId,
1398        instance_offset: &mut u64,
1399        pass: &mut wgpu::RenderPass<'_>,
1400    ) -> bool {
1401        let tex_info = self.atlas.get_texture_info(texture_id);
1402        let data = unsafe { Self::instance_bytes(sprites) };
1403        self.draw_instances_with_texture(
1404            data,
1405            sprites.len() as u32,
1406            &tex_info.view,
1407            &self.resources().pipelines.mono_sprites,
1408            instance_offset,
1409            pass,
1410        )
1411    }
1412
1413    fn draw_subpixel_sprites(
1414        &self,
1415        sprites: &[SubpixelSprite],
1416        texture_id: AtlasTextureId,
1417        instance_offset: &mut u64,
1418        pass: &mut wgpu::RenderPass<'_>,
1419    ) -> bool {
1420        let tex_info = self.atlas.get_texture_info(texture_id);
1421        let data = unsafe { Self::instance_bytes(sprites) };
1422        let resources = self.resources();
1423        let pipeline = resources
1424            .pipelines
1425            .subpixel_sprites
1426            .as_ref()
1427            .unwrap_or(&resources.pipelines.mono_sprites);
1428        self.draw_instances_with_texture(
1429            data,
1430            sprites.len() as u32,
1431            &tex_info.view,
1432            pipeline,
1433            instance_offset,
1434            pass,
1435        )
1436    }
1437
1438    fn draw_polychrome_sprites(
1439        &self,
1440        sprites: &[PolychromeSprite],
1441        texture_id: AtlasTextureId,
1442        instance_offset: &mut u64,
1443        pass: &mut wgpu::RenderPass<'_>,
1444    ) -> bool {
1445        let tex_info = self.atlas.get_texture_info(texture_id);
1446        let data = unsafe { Self::instance_bytes(sprites) };
1447        self.draw_instances_with_texture(
1448            data,
1449            sprites.len() as u32,
1450            &tex_info.view,
1451            &self.resources().pipelines.poly_sprites,
1452            instance_offset,
1453            pass,
1454        )
1455    }
1456
1457    fn draw_instances(
1458        &self,
1459        data: &[u8],
1460        instance_count: u32,
1461        pipeline: &wgpu::RenderPipeline,
1462        instance_offset: &mut u64,
1463        pass: &mut wgpu::RenderPass<'_>,
1464    ) -> bool {
1465        if instance_count == 0 {
1466            return true;
1467        }
1468        let Some((offset, size)) = self.write_to_instance_buffer(instance_offset, data) else {
1469            return false;
1470        };
1471        let resources = self.resources();
1472        let bind_group = resources
1473            .device
1474            .create_bind_group(&wgpu::BindGroupDescriptor {
1475                label: None,
1476                layout: &resources.bind_group_layouts.instances,
1477                entries: &[wgpu::BindGroupEntry {
1478                    binding: 0,
1479                    resource: self.instance_binding(offset, size),
1480                }],
1481            });
1482        pass.set_pipeline(pipeline);
1483        pass.set_bind_group(0, &resources.globals_bind_group, &[]);
1484        pass.set_bind_group(1, &bind_group, &[]);
1485        pass.draw(0..4, 0..instance_count);
1486        true
1487    }
1488
1489    fn draw_instances_with_texture(
1490        &self,
1491        data: &[u8],
1492        instance_count: u32,
1493        texture_view: &wgpu::TextureView,
1494        pipeline: &wgpu::RenderPipeline,
1495        instance_offset: &mut u64,
1496        pass: &mut wgpu::RenderPass<'_>,
1497    ) -> bool {
1498        if instance_count == 0 {
1499            return true;
1500        }
1501        let Some((offset, size)) = self.write_to_instance_buffer(instance_offset, data) else {
1502            return false;
1503        };
1504        let resources = self.resources();
1505        let bind_group = resources
1506            .device
1507            .create_bind_group(&wgpu::BindGroupDescriptor {
1508                label: None,
1509                layout: &resources.bind_group_layouts.instances_with_texture,
1510                entries: &[
1511                    wgpu::BindGroupEntry {
1512                        binding: 0,
1513                        resource: self.instance_binding(offset, size),
1514                    },
1515                    wgpu::BindGroupEntry {
1516                        binding: 1,
1517                        resource: wgpu::BindingResource::TextureView(texture_view),
1518                    },
1519                    wgpu::BindGroupEntry {
1520                        binding: 2,
1521                        resource: wgpu::BindingResource::Sampler(&resources.atlas_sampler),
1522                    },
1523                ],
1524            });
1525        pass.set_pipeline(pipeline);
1526        pass.set_bind_group(0, &resources.globals_bind_group, &[]);
1527        pass.set_bind_group(1, &bind_group, &[]);
1528        pass.draw(0..4, 0..instance_count);
1529        true
1530    }
1531
1532    unsafe fn instance_bytes<T>(instances: &[T]) -> &[u8] {
1533        unsafe {
1534            std::slice::from_raw_parts(
1535                instances.as_ptr() as *const u8,
1536                std::mem::size_of_val(instances),
1537            )
1538        }
1539    }
1540
1541    fn draw_paths_from_intermediate(
1542        &self,
1543        paths: &[Path<ScaledPixels>],
1544        instance_offset: &mut u64,
1545        pass: &mut wgpu::RenderPass<'_>,
1546    ) -> bool {
1547        let first_path = &paths[0];
1548        let sprites: Vec<PathSprite> = if paths.last().map(|p| &p.order) == Some(&first_path.order)
1549        {
1550            paths
1551                .iter()
1552                .map(|p| PathSprite {
1553                    bounds: p.clipped_bounds(),
1554                })
1555                .collect()
1556        } else {
1557            let mut bounds = first_path.clipped_bounds();
1558            for path in paths.iter().skip(1) {
1559                bounds = bounds.union(&path.clipped_bounds());
1560            }
1561            vec![PathSprite { bounds }]
1562        };
1563
1564        let resources = self.resources();
1565        let Some(path_intermediate_view) = resources.path_intermediate_view.as_ref() else {
1566            return true;
1567        };
1568
1569        let sprite_data = unsafe { Self::instance_bytes(&sprites) };
1570        self.draw_instances_with_texture(
1571            sprite_data,
1572            sprites.len() as u32,
1573            path_intermediate_view,
1574            &resources.pipelines.paths,
1575            instance_offset,
1576            pass,
1577        )
1578    }
1579
1580    fn draw_paths_to_intermediate(
1581        &self,
1582        encoder: &mut wgpu::CommandEncoder,
1583        paths: &[Path<ScaledPixels>],
1584        instance_offset: &mut u64,
1585    ) -> bool {
1586        let mut vertices = Vec::new();
1587        for path in paths {
1588            let bounds = path.clipped_bounds();
1589            vertices.extend(path.vertices.iter().map(|v| PathRasterizationVertex {
1590                xy_position: v.xy_position,
1591                st_position: v.st_position,
1592                color: path.color,
1593                bounds,
1594            }));
1595        }
1596
1597        if vertices.is_empty() {
1598            return true;
1599        }
1600
1601        let vertex_data = unsafe { Self::instance_bytes(&vertices) };
1602        let Some((vertex_offset, vertex_size)) =
1603            self.write_to_instance_buffer(instance_offset, vertex_data)
1604        else {
1605            return false;
1606        };
1607
1608        let resources = self.resources();
1609        let data_bind_group = resources
1610            .device
1611            .create_bind_group(&wgpu::BindGroupDescriptor {
1612                label: Some("path_rasterization_bind_group"),
1613                layout: &resources.bind_group_layouts.instances,
1614                entries: &[wgpu::BindGroupEntry {
1615                    binding: 0,
1616                    resource: self.instance_binding(vertex_offset, vertex_size),
1617                }],
1618            });
1619
1620        let Some(path_intermediate_view) = resources.path_intermediate_view.as_ref() else {
1621            return true;
1622        };
1623
1624        let (target_view, resolve_target) = if let Some(ref msaa_view) = resources.path_msaa_view {
1625            (msaa_view, Some(path_intermediate_view))
1626        } else {
1627            (path_intermediate_view, None)
1628        };
1629
1630        {
1631            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1632                label: Some("path_rasterization_pass"),
1633                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1634                    view: target_view,
1635                    resolve_target,
1636                    ops: wgpu::Operations {
1637                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
1638                        store: wgpu::StoreOp::Store,
1639                    },
1640                    depth_slice: None,
1641                })],
1642                depth_stencil_attachment: None,
1643                ..Default::default()
1644            });
1645
1646            pass.set_pipeline(&resources.pipelines.path_rasterization);
1647            pass.set_bind_group(0, &resources.path_globals_bind_group, &[]);
1648            pass.set_bind_group(1, &data_bind_group, &[]);
1649            pass.draw(0..vertices.len() as u32, 0..1);
1650        }
1651
1652        true
1653    }
1654
1655    fn grow_instance_buffer(&mut self) {
1656        let new_capacity = (self.instance_buffer_capacity * 2).min(self.max_buffer_size);
1657        log::info!("increased instance buffer size to {}", new_capacity);
1658        let resources = self.resources_mut();
1659        resources.instance_buffer = resources.device.create_buffer(&wgpu::BufferDescriptor {
1660            label: Some("instance_buffer"),
1661            size: new_capacity,
1662            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
1663            mapped_at_creation: false,
1664        });
1665        self.instance_buffer_capacity = new_capacity;
1666    }
1667
1668    fn write_to_instance_buffer(
1669        &self,
1670        instance_offset: &mut u64,
1671        data: &[u8],
1672    ) -> Option<(u64, NonZeroU64)> {
1673        let offset = (*instance_offset).next_multiple_of(self.storage_buffer_alignment);
1674        let size = (data.len() as u64).max(16);
1675        if offset + size > self.instance_buffer_capacity {
1676            return None;
1677        }
1678        let resources = self.resources();
1679        resources
1680            .queue
1681            .write_buffer(&resources.instance_buffer, offset, data);
1682        *instance_offset = offset + size;
1683        Some((offset, NonZeroU64::new(size).expect("size is at least 16")))
1684    }
1685
1686    fn instance_binding(&self, offset: u64, size: NonZeroU64) -> wgpu::BindingResource<'_> {
1687        // SVGA3D can produce transparent quads when successive draws bind small
1688        // ranges of the same storage buffer. Expose the available buffer tail on
1689        // this adapter; draw counts still restrict access to each batch's data.
1690        let size = instance_binding_size(
1691            self.instance_buffer_capacity,
1692            offset,
1693            size,
1694            self.expanded_instance_binding_limit,
1695        );
1696        wgpu::BindingResource::Buffer(wgpu::BufferBinding {
1697            buffer: &self.resources().instance_buffer,
1698            offset,
1699            size: Some(size),
1700        })
1701    }
1702
1703    /// Mark the surface as unconfigured so rendering is skipped until a new
1704    /// surface is provided via [`replace_surface`](Self::replace_surface).
1705    ///
1706    /// This does **not** drop the renderer — the device, queue, atlas, and
1707    /// pipelines stay alive.  Use this when the native window is destroyed
1708    /// (e.g. Android `TerminateWindow`) but you intend to re-create the
1709    /// surface later without losing cached atlas textures.
1710    pub fn unconfigure_surface(&mut self) {
1711        self.surface_configured = false;
1712        // Drop intermediate textures since they reference the old surface size.
1713        if let Some(res) = self.resources.as_mut() {
1714            res.invalidate_intermediate_textures();
1715        }
1716    }
1717
1718    /// Replace the wgpu surface with a new one (e.g. after Android destroys
1719    /// and recreates the native window).  Keeps the device, queue, atlas, and
1720    /// all pipelines intact so cached `AtlasTextureId`s remain valid.
1721    ///
1722    /// The `instance` **must** be the same [`wgpu::Instance`] that was used to
1723    /// create the adapter and device (i.e. from the [`WgpuContext`]).  Using a
1724    /// different instance will cause a "Device does not exist" panic because
1725    /// the wgpu device is bound to its originating instance.
1726    #[cfg(not(target_family = "wasm"))]
1727    pub fn replace_surface<W: HasWindowHandle>(
1728        &mut self,
1729        window: &W,
1730        config: WgpuSurfaceConfig,
1731        instance: &wgpu::Instance,
1732    ) -> anyhow::Result<()> {
1733        let window_handle = window
1734            .window_handle()
1735            .map_err(|e| anyhow::anyhow!("Failed to get window handle: {e}"))?;
1736
1737        let surface = create_surface(instance, window_handle.as_raw())?;
1738
1739        let width = (config.size.width.0 as u32).max(1);
1740        let height = (config.size.height.0 as u32).max(1);
1741
1742        let alpha_mode = if config.transparent {
1743            self.transparent_alpha_mode
1744        } else {
1745            self.opaque_alpha_mode
1746        };
1747
1748        self.surface_config.width = width;
1749        self.surface_config.height = height;
1750        self.surface_config.alpha_mode = alpha_mode;
1751        if let Some(mode) = config.preferred_present_mode {
1752            self.surface_config.present_mode = mode;
1753        }
1754
1755        {
1756            let res = self
1757                .resources
1758                .as_mut()
1759                .expect("GPU resources not available");
1760            surface.configure(&res.device, &self.surface_config);
1761            res.surface = surface;
1762
1763            // Invalidate intermediate textures — they'll be recreated lazily.
1764            res.invalidate_intermediate_textures();
1765        }
1766
1767        self.surface_configured = true;
1768
1769        Ok(())
1770    }
1771
1772    pub fn destroy(&mut self) {
1773        // Release surface-bound GPU resources eagerly so the underlying native
1774        // window can be destroyed before the renderer itself is dropped.
1775        self.resources.take();
1776    }
1777
1778    /// Returns true if the GPU device was lost and recovery is needed.
1779    pub fn device_lost(&self) -> bool {
1780        self.device_lost.load(std::sync::atomic::Ordering::SeqCst)
1781    }
1782
1783    /// Returns true if a redraw is needed because GPU state was cleared.
1784    /// Calling this method clears the flag.
1785    pub fn needs_redraw(&mut self) -> bool {
1786        std::mem::take(&mut self.needs_redraw)
1787    }
1788
1789    /// Recovers from a lost GPU device by recreating the renderer with a new context.
1790    ///
1791    /// Call this after detecting `device_lost()` returns true.
1792    ///
1793    /// This method coordinates recovery across multiple windows:
1794    /// - The first window to call this will recreate the shared context
1795    /// - Subsequent windows will adopt the already-recovered context
1796    #[cfg(not(target_family = "wasm"))]
1797    pub fn recover<W>(&mut self, window: &W) -> anyhow::Result<()>
1798    where
1799        W: HasWindowHandle + HasDisplayHandle + std::fmt::Debug + Send + Sync + Clone + 'static,
1800    {
1801        let gpu_context = self.context.as_ref().expect("recover requires gpu_context");
1802
1803        // Check if another window already recovered the context
1804        let needs_new_context = gpu_context
1805            .borrow()
1806            .as_ref()
1807            .is_none_or(|ctx| ctx.device_lost());
1808
1809        let window_handle = window
1810            .window_handle()
1811            .map_err(|e| anyhow::anyhow!("Failed to get window handle: {e}"))?;
1812
1813        let surface = if needs_new_context {
1814            log::warn!("GPU device lost, recreating context...");
1815
1816            // Drop old resources to release Arc<Device>/Arc<Queue> and GPU resources
1817            self.resources = None;
1818            *gpu_context.borrow_mut() = None;
1819
1820            // Wait briefly for the GPU driver to stabilize, then try to
1821            // recreate the context without software renderers. If this fails
1822            // the caller should request another frame and retry — the real GPU
1823            // may need more time to come back (e.g. after suspend/resume).
1824            std::thread::sleep(std::time::Duration::from_millis(350));
1825
1826            let instance = WgpuContext::instance(Box::new(window.clone()));
1827            let surface = create_surface(&instance, window_handle.as_raw())?;
1828            let new_context =
1829                WgpuContext::new_rejecting_software(instance, &surface, self.compositor_gpu)?;
1830            *gpu_context.borrow_mut() = Some(new_context);
1831            surface
1832        } else {
1833            let ctx_ref = gpu_context.borrow();
1834            let instance = &ctx_ref.as_ref().unwrap().instance;
1835            create_surface(instance, window_handle.as_raw())?
1836        };
1837
1838        let config = WgpuSurfaceConfig {
1839            size: gpui::Size {
1840                width: gpui::DevicePixels(self.surface_config.width as i32),
1841                height: gpui::DevicePixels(self.surface_config.height as i32),
1842            },
1843            transparent: self.surface_config.alpha_mode != wgpu::CompositeAlphaMode::Opaque,
1844            preferred_present_mode: Some(self.surface_config.present_mode),
1845        };
1846        let gpu_context = Rc::clone(gpu_context);
1847        let ctx_ref = gpu_context.borrow();
1848        let context = ctx_ref.as_ref().expect("context should exist");
1849
1850        self.resources = None;
1851        self.atlas.handle_device_lost(context);
1852
1853        *self = Self::new_internal(
1854            Some(gpu_context.clone()),
1855            context,
1856            surface,
1857            config,
1858            self.compositor_gpu,
1859            self.atlas.clone(),
1860        )?;
1861
1862        log::info!("GPU recovery complete");
1863        Ok(())
1864    }
1865}
1866
1867fn instance_binding_size(
1868    capacity: u64,
1869    offset: u64,
1870    size: NonZeroU64,
1871    expanded_limit: Option<u64>,
1872) -> NonZeroU64 {
1873    expanded_limit
1874        .and_then(|limit| NonZeroU64::new((capacity - offset).min(limit)))
1875        .filter(|expanded| *expanded >= size)
1876        .unwrap_or(size)
1877}
1878
1879#[cfg(test)]
1880mod tests {
1881    use super::instance_binding_size;
1882    use std::num::NonZeroU64;
1883
1884    #[test]
1885    fn instance_binding_expansion_respects_buffer_and_device_limits() {
1886        let size = NonZeroU64::new(160).unwrap();
1887        assert_eq!(instance_binding_size(4096, 256, size, None), size);
1888        assert_eq!(
1889            instance_binding_size(4096, 256, size, Some(2048)).get(),
1890            2048
1891        );
1892        assert_eq!(
1893            instance_binding_size(4096, 3840, size, Some(2048)).get(),
1894            256
1895        );
1896        assert_eq!(instance_binding_size(4096, 3936, size, Some(2048)), size);
1897        // An oversized batch must retain its validation error, not be truncated.
1898        assert_eq!(instance_binding_size(4096, 0, size, Some(128)), size);
1899    }
1900}
1901
1902#[cfg(not(target_family = "wasm"))]
1903fn create_surface(
1904    instance: &wgpu::Instance,
1905    raw_window_handle: raw_window_handle::RawWindowHandle,
1906) -> anyhow::Result<wgpu::Surface<'static>> {
1907    unsafe {
1908        instance
1909            .create_surface_unsafe(wgpu::SurfaceTargetUnsafe::RawHandle {
1910                // Fall back to the display handle already provided via InstanceDescriptor::display.
1911                raw_display_handle: None,
1912                raw_window_handle,
1913            })
1914            .map_err(|e| anyhow::anyhow!("{e}"))
1915    }
1916}
1917
1918struct RenderingParameters {
1919    path_sample_count: u32,
1920    gamma_ratios: [f32; 4],
1921    grayscale_enhanced_contrast: f32,
1922    subpixel_enhanced_contrast: f32,
1923}
1924
1925impl RenderingParameters {
1926    fn new(adapter: &wgpu::Adapter, surface_format: wgpu::TextureFormat) -> Self {
1927        use std::env;
1928
1929        let format_features = adapter.get_texture_format_features(surface_format);
1930        let path_sample_count = [4, 2, 1]
1931            .into_iter()
1932            .find(|&n| format_features.flags.sample_count_supported(n))
1933            .unwrap_or(1);
1934
1935        let gamma = env::var("ZED_FONTS_GAMMA")
1936            .ok()
1937            .and_then(|v| v.parse().ok())
1938            .unwrap_or(1.8_f32)
1939            .clamp(1.0, 2.2);
1940        let gamma_ratios = get_gamma_correction_ratios(gamma);
1941
1942        let grayscale_enhanced_contrast = env::var("ZED_FONTS_GRAYSCALE_ENHANCED_CONTRAST")
1943            .ok()
1944            .and_then(|v| v.parse().ok())
1945            .unwrap_or(1.0_f32)
1946            .max(0.0);
1947
1948        let subpixel_enhanced_contrast = env::var("ZED_FONTS_SUBPIXEL_ENHANCED_CONTRAST")
1949            .ok()
1950            .and_then(|v| v.parse().ok())
1951            .unwrap_or(0.5_f32)
1952            .max(0.0);
1953
1954        Self {
1955            path_sample_count,
1956            gamma_ratios,
1957            grayscale_enhanced_contrast,
1958            subpixel_enhanced_contrast,
1959        }
1960    }
1961}