Skip to main content

egui_pop_viewport/
gpu.rs

1//! The GPU path (feature `wgpu`): scene tiles as half-float textures,
2//! drawn by an `egui_wgpu` paint callback whose shader runs the display
3//! transform's [`Stage`].
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! Call [`install`] once with the render state eframe (or a test
9//! harness) opened; from then on, viewports in that context send scene
10//! tiles here. Without it, everything takes the CPU path.
11//!
12//! - Textures are `Rgba16Float` where the adapter can sample it (else
13//!   `Rgba32Float`), one per tile, a tile never larger than the device's
14//!   `max_texture_dimension_2d`.
15//! - Texels are read with `textureLoad` (nearest): below 100 % the
16//!   source renders at the view's scale, one texel per physical pixel;
17//!   above, each image pixel is a crisp square.
18
19use std::collections::HashMap;
20use std::sync::{Arc, Mutex};
21
22use egui::Context;
23use egui_pop_core::state;
24use egui_wgpu::wgpu;
25
26/// egui-wgpu, the version the GPU path is built with.
27pub use egui_wgpu;
28
29use crate::device::{Encoding, RenderDevice, Resource};
30use crate::display::{self, ColorSpace, DisplayTarget, Stage, SurfaceFormat, TargetSource};
31use crate::tiles::{Device, GpuData, GpuQueue};
32
33/// What [`install`] found.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub struct GpuInfo {
36    /// The largest texture side the device takes.
37    pub max_texture_side: u32,
38    /// Tiles are half floats (else 32-bit floats).
39    pub half_float: bool,
40    /// The surface encodes sRGB on write (the shader then writes linear).
41    pub target_is_srgb: bool,
42}
43
44/// What every tile pipeline shares: the draw's uniform, the vertex
45/// stage, the transfers and the display stage.
46const COMMON: &str = r#"
47struct Draw {
48    dst: vec4<f32>,
49    sizes: vec4<f32>,
50    m0: vec4<f32>,
51    m1: vec4<f32>,
52    m2: vec4<f32>,
53    params: vec4<f32>,
54    extra: vec4<f32>,
55    // Uploaded tiles and textures: the tile's texel origin, 0, the mode;
56    // buffers: the tile's first float, floats a row, channels, the mode.
57    tile_layout: vec4<u32>,
58};
59
60@group(0) @binding(0) var<uniform> d: Draw;
61
62struct V {
63    @builtin(position) pos: vec4<f32>,
64};
65
66@vertex
67fn vs(@builtin(vertex_index) i: u32) -> V {
68    var corners = array<vec2<f32>, 6>(
69        vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0),
70        vec2<f32>(0.0, 1.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0),
71    );
72    let p = mix(d.dst.xy, d.dst.zw, corners[i]);
73    var out: V;
74    out.pos = vec4<f32>(p.x / d.sizes.x * 2.0 - 1.0, 1.0 - p.y / d.sizes.y * 2.0, 0.0, 1.0);
75    return out;
76}
77
78fn srgb_encode(v: f32) -> f32 {
79    let x = max(v, 0.0);
80    if x <= 0.0031308 {
81        return x * 12.92;
82    }
83    return 1.055 * pow(x, 1.0 / 2.4) - 0.055;
84}
85
86fn srgb_decode(v: f32) -> f32 {
87    if v <= 0.04045 {
88        return v / 12.92;
89    }
90    return pow((v + 0.055) / 1.055, 2.4);
91}
92
93fn pq_encode(nits: f32) -> f32 {
94    let m1 = 2610.0 / 16384.0;
95    let m2 = 2523.0 / 4096.0 * 128.0;
96    let c1 = 3424.0 / 4096.0;
97    let c2 = 2413.0 / 4096.0 * 32.0;
98    let c3 = 2392.0 / 4096.0 * 32.0;
99    let y = pow(clamp(nits / 10000.0, 0.0, 1.0), m1);
100    return pow((c1 + c2 * y) / (1.0 + c3 * y), m2);
101}
102
103fn hlg_oetf(e: f32) -> f32 {
104    let x = clamp(e, 0.0, 1.0);
105    if x <= 1.0 / 12.0 {
106        return sqrt(3.0 * x);
107    }
108    let a = 0.17883277;
109    return a * log(12.0 * x - (1.0 - 4.0 * a)) + 0.5599107;
110}
111
112// The transfers of `display::Transfer`, by code; `white` is the nits of
113// SDR white (PQ is absolute).
114fn encode(v: f32, code: u32, white: f32) -> f32 {
115    if code == 1u {
116        return pow(max(v, 0.0), 1.0 / 2.2);
117    }
118    if code == 2u {
119        return v;
120    }
121    if code == 3u {
122        return pq_encode(max(v, 0.0) * white);
123    }
124    if code == 4u {
125        return hlg_oetf(max(v, 0.0) * 0.26496256);
126    }
127    if code == 5u {
128        return sign(v) * srgb_encode(abs(v));
129    }
130    return srgb_encode(v);
131}
132
133// The tile's texel under a fragment, from the tile's top left.
134fn texel_at(pos: vec2<f32>) -> vec2<i32> {
135    let size = d.sizes.zw;
136    let t = (pos - d.dst.xy) / (d.dst.zw - d.dst.xy) * size;
137    return clamp(vec2<i32>(floor(t)), vec2<i32>(0, 0), vec2<i32>(size) - vec2<i32>(1, 1));
138}
139
140// A value read to the colour written. Mode 0: scene-referred, through
141// the display stage; 1: display-encoded, as it is; 2: display-encoded
142// in an sRGB texture, whose read decoded it: encoded again.
143fn shade(s: vec3<f32>) -> vec4<f32> {
144    let mode = d.tile_layout.w;
145    var out = s;
146    if mode == 0u {
147        var rgb = vec3<f32>(dot(d.m0.xyz, s), dot(d.m1.xyz, s), dot(d.m2.xyz, s));
148        rgb = clamp(rgb, vec3<f32>(d.params.x), vec3<f32>(d.params.y));
149        let code = u32(d.params.z);
150        let white = d.extra.x;
151        out = vec3<f32>(encode(rgb.r, code, white), encode(rgb.g, code, white), encode(rgb.b, code, white));
152    } else if mode == 2u {
153        out = vec3<f32>(srgb_encode(s.r), srgb_encode(s.g), srgb_encode(s.b));
154    }
155    if d.params.w > 0.5 {
156        // The surface encodes sRGB itself: hand it what decodes to `out`.
157        out = vec3<f32>(srgb_decode(out.r), srgb_decode(out.g), srgb_decode(out.b));
158    }
159    return vec4<f32>(out, 1.0);
160}
161"#;
162
163/// Tiles in textures: uploaded ones and device textures; and the hole
164/// an image surface shows through.
165const TEXTURE: &str = r#"
166@group(1) @binding(0) var tex: texture_2d<f32>;
167
168@fragment
169fn fs(v: V) -> @location(0) vec4<f32> {
170    let texel = texel_at(v.pos.xy) + vec2<i32>(d.tile_layout.xy);
171    return shade(textureLoad(tex, texel, 0).rgb);
172}
173
174// A triangle over the whole target, for the hole an image surface below
175// the window shows through (the scissor keeps it to the image).
176@vertex
177fn vs_full(@builtin(vertex_index) i: u32) -> V {
178    var corners = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
179    var out: V;
180    out.pos = vec4<f32>(corners[i], 0.0, 1.0);
181    return out;
182}
183
184@fragment
185fn fs_hole() -> @location(0) vec4<f32> {
186    return vec4<f32>(0.0, 0.0, 0.0, 0.0);
187}
188"#;
189
190/// Device tiles in storage buffers of `f32`, read in place.
191const BUFFER: &str = r#"
192@group(1) @binding(0) var<storage, read> buf: array<f32>;
193
194@fragment
195fn fs(v: V) -> @location(0) vec4<f32> {
196    let t = vec2<u32>(texel_at(v.pos.xy));
197    let channels = d.tile_layout.z;
198    let i = d.tile_layout.x + t.y * d.tile_layout.y + t.x * channels;
199    var s = vec3<f32>(buf[i]);
200    if channels >= 3u {
201        s = vec3<f32>(buf[i], buf[i + 1u], buf[i + 2u]);
202    }
203    return shade(s);
204}
205"#;
206
207/// Bytes of one draw's uniform.
208const UNIFORM_SIZE: u64 = 8 * 16;
209
210struct Slot {
211    buffer: wgpu::Buffer,
212    group: wgpu::BindGroup,
213    capacity: usize,
214}
215
216/// The tile pipelines for one target format: textures, and storage
217/// buffers where the adapter reads them in a fragment shader.
218pub(crate) struct Pipelines {
219    texture: wgpu::RenderPipeline,
220    buffer: Option<wgpu::RenderPipeline>,
221}
222
223/// A tile bound for drawing: its bind group, which pipeline reads it,
224/// and its uniform's `layout`.
225struct Bound {
226    group: wgpu::BindGroup,
227    buffer: bool,
228    layout: [u32; 4],
229    /// What a device tile keeps alive while it is held
230    /// ([`DeviceTile::keep`](crate::device::DeviceTile::keep)).
231    _keep: Vec<crate::device::Keep>,
232}
233
234/// The shader modules and pipeline layouts the tile pipelines are built
235/// from.
236struct Modules {
237    texture: (wgpu::ShaderModule, wgpu::PipelineLayout),
238    buffer: Option<(wgpu::ShaderModule, wgpu::PipelineLayout)>,
239}
240
241impl Modules {
242    fn pipelines(&self, device: &wgpu::Device, format: wgpu::TextureFormat) -> Pipelines {
243        let (shader, layout) = &self.texture;
244        Pipelines {
245            texture: render_pipeline(device, shader, layout, ["vs", "fs"], format),
246            buffer: self.buffer.as_ref().map(|(shader, layout)| {
247                render_pipeline(device, shader, layout, ["vs", "fs"], format)
248            }),
249        }
250    }
251}
252
253pub(crate) struct Resources {
254    pipelines: Pipelines,
255    // What an image surface (`wayland`) draws with: its hole, and on Linux
256    // the tile pipeline per surface format, built from the same shader and
257    // layout.
258    /// Writes transparent black over the image, in the window's format.
259    #[cfg(feature = "wayland")]
260    hole: wgpu::RenderPipeline,
261    modules: Modules,
262    /// The tile pipelines for each image surface format.
263    #[cfg(all(feature = "wayland", target_os = "linux"))]
264    pub(crate) image_pipelines: HashMap<wgpu::TextureFormat, Pipelines>,
265    uniform_layout: wgpu::BindGroupLayout,
266    texture_layout: wgpu::BindGroupLayout,
267    /// The buffer tiles' layout, `None` where the adapter cannot read
268    /// storage buffers in a fragment shader.
269    buffer_layout: Option<wgpu::BindGroupLayout>,
270    stride: u64,
271    format: wgpu::TextureFormat,
272    target_is_srgb: bool,
273    /// The device's storage binding offset alignment.
274    storage_align: u64,
275    textures: HashMap<u64, Bound>,
276    slots: HashMap<u64, Slot>,
277    /// The queues of the tile caches whose tiles this render state
278    /// binds: a closed one (its cache dropped) has its textures released
279    /// by the next paint of any viewport here, then is forgotten.
280    queues: Vec<Arc<Mutex<GpuQueue>>>,
281}
282
283/// The GPU path's device, when installed.
284const DEVICE: state::Slot<Device> = state::Slot::opaque("viewport.gpu.device");
285/// The GPU path takes half-float texels.
286const HALF_FLOAT: state::Slot<bool> = state::Slot::new("viewport.gpu.half_float");
287/// The render device, for device tiles.
288const RENDER: state::Slot<RenderDevice> = state::Slot::opaque("viewport.gpu.render");
289
290/// The render device of the GPU path installed in `ctx`: the device a
291/// [`DeviceTile`](crate::device::DeviceTile) must be created on, and what
292/// it can read. `None` without a GPU path. Read when called: set by
293/// [`install`] at once, not at the next frame.
294pub fn render_device(ctx: &Context) -> Option<RenderDevice> {
295    RENDER.get(ctx)
296}
297
298/// The GPU path's device, when installed in `ctx`.
299pub(crate) fn installed(ctx: &Context) -> Option<Device> {
300    DEVICE.get(ctx)
301}
302
303/// Whether the GPU path installed in `ctx` takes half-float texels.
304pub(crate) fn half_float(ctx: &Context) -> bool {
305    HALF_FLOAT.get(ctx).unwrap_or(false)
306}
307
308/// The display stage's surface format for a wgpu one.
309pub fn surface_format(format: wgpu::TextureFormat) -> SurfaceFormat {
310    use wgpu::TextureFormat as F;
311    match format {
312        F::Rgba8UnormSrgb | F::Bgra8UnormSrgb => SurfaceFormat::Rgba8UnormSrgb,
313        F::Rgba8Unorm | F::Bgra8Unorm => SurfaceFormat::Rgba8Unorm,
314        F::Rgb10a2Unorm => SurfaceFormat::Rgb10a2Unorm,
315        F::Rgba16Float => SurfaceFormat::Rgba16Float,
316        _ => SurfaceFormat::Other,
317    }
318}
319
320/// The display stage's colour space for a wgpu one; `Auto` as wgpu
321/// resolves it (extended linear on half floats, sRGB otherwise).
322pub fn color_space(space: wgpu::SurfaceColorSpace, format: wgpu::TextureFormat) -> ColorSpace {
323    use wgpu::SurfaceColorSpace as S;
324    match space {
325        S::Auto if format == wgpu::TextureFormat::Rgba16Float => ColorSpace::ExtendedSrgbLinear,
326        S::ExtendedSrgbLinear => ColorSpace::ExtendedSrgbLinear,
327        S::ExtendedSrgb => ColorSpace::ExtendedSrgb,
328        S::DisplayP3 => ColorSpace::DisplayP3,
329        S::ExtendedDisplayP3 => ColorSpace::ExtendedDisplayP3,
330        S::Bt2100Pq => ColorSpace::Bt2100Pq,
331        S::Bt2100Hlg => ColorSpace::Bt2100Hlg,
332        _ => ColorSpace::Srgb,
333    }
334}
335
336pub(crate) fn to_wgpu(space: ColorSpace) -> wgpu::SurfaceColorSpace {
337    use wgpu::SurfaceColorSpace as S;
338    match space {
339        ColorSpace::Srgb => S::Srgb,
340        ColorSpace::ExtendedSrgbLinear => S::ExtendedSrgbLinear,
341        ColorSpace::ExtendedSrgb => S::ExtendedSrgb,
342        ColorSpace::DisplayP3 => S::DisplayP3,
343        ColorSpace::ExtendedDisplayP3 => S::ExtendedDisplayP3,
344        ColorSpace::Bt2100Pq => S::Bt2100Pq,
345        ColorSpace::Bt2100Hlg => S::Bt2100Hlg,
346    }
347}
348
349/// What a surface configured with `format` and `space` expects, as
350/// declared by wgpu's window system integration; `headroom` is the
351/// display's (wgpu's `DisplayHdrInfo`), 1.0 when unknown.
352pub fn surface_target(
353    format: wgpu::TextureFormat,
354    space: wgpu::SurfaceColorSpace,
355    headroom: f32,
356) -> DisplayTarget {
357    DisplayTarget::for_color_space(
358        color_space(space, format),
359        surface_format(format),
360        headroom,
361        TargetSource::Wsi,
362    )
363}
364
365/// Which surfaces a host may configure for a wanted target.
366#[derive(Clone, Copy, Debug, PartialEq, Eq)]
367pub enum SurfacePolicy {
368    /// Only colour spaces egui's renderer draws the interface faithfully
369    /// on (sRGB, extended sRGB): the window holds egui's interface.
370    EguiCompatible,
371    /// Any colour space: the host composes the interface itself (or the
372    /// surface holds only the image).
373    Any,
374}
375
376/// The surface configuration path for a host that configures its own
377/// surface (eframe 0.36 configures 8-bit sRGB and offers no choice):
378/// the format and colour space to configure for `wanted`, among what the
379/// surface's capabilities offer, and what the viewport will draw for
380/// once configured. Prefers what carries the wanted gamut and headroom,
381/// then fewer bits.
382pub fn choose_surface(
383    caps: &wgpu::SurfaceCapabilities,
384    wanted: &DisplayTarget,
385    policy: SurfacePolicy,
386    headroom: f32,
387) -> Option<(wgpu::TextureFormat, wgpu::SurfaceColorSpace, DisplayTarget)> {
388    let mut best: Option<(u8, wgpu::TextureFormat, ColorSpace)> = None;
389    for &format in &caps.formats {
390        let supported = caps.color_spaces(format);
391        for space in ColorSpace::ALL {
392            if policy == SurfacePolicy::EguiCompatible && !space.egui_draws_faithfully() {
393                continue;
394            }
395            if !supported.contains(color_space_flag(space)) {
396                continue;
397            }
398            let target = DisplayTarget::for_color_space(
399                space,
400                surface_format(format),
401                headroom,
402                TargetSource::Wsi,
403            );
404            if !target.is_supported() {
405                continue;
406            }
407            // Carrying what is wanted first, then the narrowest format.
408            let score = if target.missing(wanted).is_none() {
409                100
410            } else {
411                0
412            } + (if space == ColorSpace::Srgb { 10 } else { 0 })
413                + (32 - surface_format(format).bits().min(32) / 2);
414            if best.is_none_or(|b| score > b.0) {
415                best = Some((score, format, space));
416            }
417        }
418    }
419    best.map(|(_, format, space)| {
420        let target = DisplayTarget::for_color_space(
421            space,
422            surface_format(format),
423            headroom,
424            TargetSource::Wsi,
425        );
426        (format, to_wgpu(space), target)
427    })
428}
429
430pub(crate) fn color_space_flag(space: ColorSpace) -> wgpu::SurfaceColorSpaces {
431    use wgpu::SurfaceColorSpaces as F;
432    match space {
433        ColorSpace::Srgb => F::SRGB,
434        ColorSpace::ExtendedSrgbLinear => F::EXTENDED_SRGB_LINEAR,
435        ColorSpace::ExtendedSrgb => F::EXTENDED_SRGB,
436        ColorSpace::DisplayP3 => F::DISPLAY_P3,
437        ColorSpace::ExtendedDisplayP3 => F::EXTENDED_DISPLAY_P3,
438        ColorSpace::Bt2100Pq => F::BT2100_PQ,
439        ColorSpace::Bt2100Hlg => F::BT2100_HLG,
440    }
441}
442
443/// Installs the GPU path on a render state; viewports in `ctx` use it
444/// from the next frame. Records what the surface expects for every
445/// window: eframe 0.36 configures `rs.target_format` with wgpu's default
446/// colour space (8-bit sRGB in practice). A host that configured its
447/// surface itself calls [`install_for_surface`].
448///
449/// Install it before the first [`Viewport::show`](crate::Viewport::show)
450/// (in eframe's app creation, from `cc.wgpu_render_state`): the first
451/// frame's tile requests then take the device path. Device tiles asked
452/// for before are refused (no GPU path) and served from their fallback,
453/// then asked for again once the render device is there.
454pub fn install(ctx: &Context, rs: &egui_wgpu::RenderState) -> GpuInfo {
455    install_for_surface(ctx, rs, wgpu::SurfaceColorSpace::Auto, 1.0)
456}
457
458/// [`install`], for a surface configured with `space` (and a display of
459/// `headroom`, 1.0 when unknown).
460pub fn install_for_surface(
461    ctx: &Context,
462    rs: &egui_wgpu::RenderState,
463    space: wgpu::SurfaceColorSpace,
464    headroom: f32,
465) -> GpuInfo {
466    display::set_default_target(ctx, surface_target(rs.target_format, space, headroom));
467    let device = &rs.device;
468    let half = rs
469        .adapter
470        .get_texture_format_features(wgpu::TextureFormat::Rgba16Float)
471        .allowed_usages
472        .contains(wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST);
473    let format = if half {
474        wgpu::TextureFormat::Rgba16Float
475    } else {
476        wgpu::TextureFormat::Rgba32Float
477    };
478    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
479        label: Some("egui-pop-viewport"),
480        source: wgpu::ShaderSource::Wgsl(format!("{COMMON}{TEXTURE}").into()),
481    });
482    let buffers = reads_fragment_storage(
483        rs.adapter.get_downlevel_capabilities().flags,
484        &device.limits(),
485    );
486    let uniform_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
487        label: Some("egui-pop-viewport.draw"),
488        entries: &[wgpu::BindGroupLayoutEntry {
489            binding: 0,
490            visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
491            ty: wgpu::BindingType::Buffer {
492                ty: wgpu::BufferBindingType::Uniform,
493                has_dynamic_offset: true,
494                min_binding_size: wgpu::BufferSize::new(UNIFORM_SIZE),
495            },
496            count: None,
497        }],
498    });
499    let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
500        label: Some("egui-pop-viewport.tile"),
501        entries: &[wgpu::BindGroupLayoutEntry {
502            binding: 0,
503            visibility: wgpu::ShaderStages::FRAGMENT,
504            ty: wgpu::BindingType::Texture {
505                sample_type: wgpu::TextureSampleType::Float { filterable: false },
506                view_dimension: wgpu::TextureViewDimension::D2,
507                multisampled: false,
508            },
509            count: None,
510        }],
511    });
512    // Without fragment storage (WebGL 2), even the buffer binding's
513    // layout fails validation: neither it nor its pipeline is created.
514    let buffer_layout = buffers.then(|| {
515        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
516            label: Some("egui-pop-viewport.device-buffer"),
517            entries: &[wgpu::BindGroupLayoutEntry {
518                binding: 0,
519                visibility: wgpu::ShaderStages::FRAGMENT,
520                ty: wgpu::BindingType::Buffer {
521                    ty: wgpu::BufferBindingType::Storage { read_only: true },
522                    has_dynamic_offset: false,
523                    min_binding_size: None,
524                },
525                count: None,
526            }],
527        })
528    });
529    let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
530        label: Some("egui-pop-viewport"),
531        bind_group_layouts: &[Some(&uniform_layout), Some(&texture_layout)],
532        ..Default::default()
533    });
534    let buffer_module = buffer_layout.as_ref().map(|buffer_layout| {
535        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
536            label: Some("egui-pop-viewport.device-buffer"),
537            source: wgpu::ShaderSource::Wgsl(format!("{COMMON}{BUFFER}").into()),
538        });
539        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
540            label: Some("egui-pop-viewport.device-buffer"),
541            bind_group_layouts: &[Some(&uniform_layout), Some(buffer_layout)],
542            ..Default::default()
543        });
544        (shader, layout)
545    });
546    #[cfg(feature = "wayland")]
547    let empty = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
548        label: Some("egui-pop-viewport.hole"),
549        ..Default::default()
550    });
551    #[cfg(feature = "wayland")]
552    let hole = render_pipeline(
553        device,
554        &shader,
555        &empty,
556        ["vs_full", "fs_hole"],
557        rs.target_format,
558    );
559    let align = u64::from(device.limits().min_uniform_buffer_offset_alignment);
560    let stride = UNIFORM_SIZE.div_ceil(align) * align;
561    let max_texture_side = device.limits().max_texture_dimension_2d;
562    let target_is_srgb = rs.target_format.is_srgb();
563    let storage_align = u64::from(device.limits().min_storage_buffer_offset_alignment);
564    let modules = Modules {
565        texture: (shader, layout),
566        buffer: buffer_module,
567    };
568    let pipelines = modules.pipelines(device, rs.target_format);
569    rs.renderer.write().callback_resources.insert(Resources {
570        pipelines,
571        #[cfg(feature = "wayland")]
572        hole,
573        modules,
574        #[cfg(all(feature = "wayland", target_os = "linux"))]
575        image_pipelines: HashMap::new(),
576        uniform_layout,
577        texture_layout,
578        buffer_layout,
579        stride,
580        format,
581        target_is_srgb,
582        storage_align,
583        textures: HashMap::new(),
584        slots: HashMap::new(),
585        queues: Vec::new(),
586    });
587    RENDER.set(
588        ctx,
589        RenderDevice {
590            device: device.clone(),
591            buffers,
592            storage_align,
593            max_binding: device.limits().max_storage_buffer_binding_size,
594        },
595    );
596    DEVICE.set(
597        ctx,
598        Device {
599            max_texture_side,
600            gpu: true,
601        },
602    );
603    HALF_FLOAT.set(ctx, half);
604    GpuInfo {
605        max_texture_side,
606        half_float: half,
607        target_is_srgb,
608    }
609}
610
611/// Whether an adapter with these downlevel `flags` and a device with
612/// these `limits` let the tile shader read a storage buffer in its
613/// fragment stage. WebGL 2 does not (no `FRAGMENT_STORAGE`, no storage
614/// buffer per stage): there, buffer device tiles are refused
615/// ([`DeviceTileError::BuffersUnsupported`](crate::device::DeviceTileError::BuffersUnsupported))
616/// and the buffer pipeline is not built.
617pub fn reads_fragment_storage(flags: wgpu::DownlevelFlags, limits: &wgpu::Limits) -> bool {
618    flags.contains(wgpu::DownlevelFlags::FRAGMENT_STORAGE)
619        && limits.max_storage_buffers_per_shader_stage > 0
620}
621
622/// A pipeline of the viewport's shader, its `[vertex, fragment]` entry
623/// points, writing `format` without blending.
624fn render_pipeline(
625    device: &wgpu::Device,
626    shader: &wgpu::ShaderModule,
627    layout: &wgpu::PipelineLayout,
628    [vertex, fragment]: [&str; 2],
629    format: wgpu::TextureFormat,
630) -> wgpu::RenderPipeline {
631    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
632        label: Some("egui-pop-viewport"),
633        layout: Some(layout),
634        vertex: wgpu::VertexState {
635            module: shader,
636            entry_point: Some(vertex),
637            compilation_options: wgpu::PipelineCompilationOptions::default(),
638            buffers: &[],
639        },
640        fragment: Some(wgpu::FragmentState {
641            module: shader,
642            entry_point: Some(fragment),
643            compilation_options: wgpu::PipelineCompilationOptions::default(),
644            targets: &[Some(wgpu::ColorTargetState {
645                format,
646                blend: None,
647                write_mask: wgpu::ColorWrites::ALL,
648            })],
649        }),
650        primitive: wgpu::PrimitiveState::default(),
651        depth_stencil: None,
652        multisample: wgpu::MultisampleState::default(),
653        multiview_mask: None,
654        cache: None,
655    })
656}
657
658impl Resources {
659    /// A tile texture's bind group (`layout`: its uniform's).
660    fn bind_tile(&self, device: &wgpu::Device, texture: &wgpu::Texture, layout: [u32; 4]) -> Bound {
661        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
662        let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
663            label: Some("egui-pop-viewport.tile"),
664            layout: &self.texture_layout,
665            entries: &[wgpu::BindGroupEntry {
666                binding: 0,
667                resource: wgpu::BindingResource::TextureView(&view),
668            }],
669        });
670        Bound {
671            group,
672            buffer: false,
673            layout,
674            _keep: Vec::new(),
675        }
676    }
677
678    /// A device tile's binding: its texture, or the rows of its buffer
679    /// the tile covers. `None` when it cannot be bound here (checked
680    /// before: another device, or buffers unreadable).
681    fn bind_device(
682        &self,
683        device: &wgpu::Device,
684        tile: &crate::device::DeviceTile,
685        size: [u32; 2],
686    ) -> Option<Bound> {
687        if tile.device() != device {
688            return None;
689        }
690        let display = tile.encoding == Encoding::Display;
691        match tile.resource() {
692            Resource::Texture(texture) => {
693                let mode = match (display, texture.format().is_srgb()) {
694                    (false, _) => 0,
695                    (true, false) => 1,
696                    (true, true) => 2,
697                };
698                let [ox, oy] = tile.origin;
699                Some(self.bind_tile(device, texture, [ox, oy, 0, mode]))
700            }
701            Resource::Buffer { buffer, layout } => {
702                self.modules.buffer.as_ref()?;
703                let buffer_layout = self.buffer_layout.as_ref()?;
704                let (offset, bytes, base) = layout.binding(tile.origin, size, self.storage_align);
705                let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
706                    label: Some("egui-pop-viewport.device-buffer"),
707                    layout: buffer_layout,
708                    entries: &[wgpu::BindGroupEntry {
709                        binding: 0,
710                        resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
711                            buffer,
712                            offset,
713                            size: wgpu::BufferSize::new(bytes),
714                        }),
715                    }],
716                });
717                Some(Bound {
718                    _keep: Vec::new(),
719                    group,
720                    buffer: true,
721                    layout: [
722                        u32::try_from(base).ok()?,
723                        layout.row_floats,
724                        layout.channels,
725                        u32::from(display),
726                    ],
727                })
728            }
729        }
730    }
731
732    /// The tile pipelines for an image surface's format, built on first
733    /// use.
734    #[cfg(all(feature = "wayland", target_os = "linux"))]
735    pub(crate) fn ensure_image_pipelines(
736        &mut self,
737        device: &wgpu::Device,
738        format: wgpu::TextureFormat,
739    ) {
740        let modules = &self.modules;
741        self.image_pipelines
742            .entry(format)
743            .or_insert_with(|| modules.pipelines(device, format));
744    }
745
746    /// The window's tile pipelines.
747    pub(crate) fn pipelines(&self) -> &Pipelines {
748        &self.pipelines
749    }
750
751    /// Draws the hole an image surface below the window shows through.
752    #[cfg(feature = "wayland")]
753    pub(crate) fn draw_hole(&self, pass: &mut wgpu::RenderPass<'_>, screen: [u32; 2]) {
754        pass.set_viewport(0.0, 0.0, screen[0] as f32, screen[1] as f32, 0.0, 1.0);
755        pass.set_pipeline(&self.hole);
756        pass.draw(0..3, 0..1);
757    }
758}
759
760/// One tile drawn by the GPU path.
761#[derive(Clone, Copy, Debug)]
762pub(crate) struct GpuDraw {
763    pub texture: u64,
764    /// Where, in physical pixels of the window.
765    pub dst: [f32; 4],
766    pub size: [u32; 2],
767}
768
769/// One viewport side's GPU tiles for a frame.
770pub(crate) struct TilePaint {
771    pub slot: u64,
772    pub queue: Arc<Mutex<GpuQueue>>,
773    pub draws: Vec<GpuDraw>,
774    pub stage: Stage,
775}
776
777impl TilePaint {
778    /// Takes in the tiles uploaded and freed since the last frame.
779    pub(crate) fn sync_textures(
780        &self,
781        device: &wgpu::Device,
782        queue: &wgpu::Queue,
783        r: &mut Resources,
784    ) {
785        // On the render thread: one texture per tile uploaded, and the
786        // f16 conversion of tiles not prepared by the delivering thread.
787        profiling::scope!("pop.tiles.gpu_prepare");
788        // This cache's queue, known here before anything is bound from
789        // it; the textures of caches dropped since released, with what
790        // their device tiles keep alive. Per render state: another
791        // renderer's paint never sees these textures.
792        if !r.queues.iter().any(|q| Arc::ptr_eq(q, &self.queue)) {
793            r.queues.push(self.queue.clone());
794        }
795        let textures = &mut r.textures;
796        r.queues.retain(|q| {
797            let mut q = q.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
798            if !q.closed {
799                return true;
800            }
801            for id in q.frees.drain(..) {
802                textures.remove(&id);
803            }
804            q.uploads.clear();
805            false
806        });
807        let (uploads, frees) = self
808            .queue
809            .lock()
810            .unwrap_or_else(std::sync::PoisonError::into_inner)
811            .drain();
812        if uploads.is_empty() && frees.is_empty() {
813            return;
814        }
815        for id in frees {
816            r.textures.remove(&id);
817        }
818        let mut copied = crate::tiles::Transfers::default();
819        for (id, size, data) in uploads {
820            let half = r.format == wgpu::TextureFormat::Rgba16Float;
821            let bpp: u32 = if half { 8 } else { 16 };
822            let bytes = match data {
823                GpuData::Scene(data) => crate::source::texels(&data, half),
824                GpuData::Texels(bytes) => bytes,
825                GpuData::Device(mut tile) => {
826                    // On the render device: bound as it is, what it keeps
827                    // held with the binding until the tile is released.
828                    if let Some(mut bound) = r.bind_device(device, &tile, size) {
829                        bound._keep = std::mem::take(&mut tile.keep);
830                        r.textures.insert(id, bound);
831                        copied.bound += 1;
832                    }
833                    continue;
834                }
835            };
836            // Prepared for another format (cannot happen while the
837            // device stays): left out, the tile is not drawn.
838            if bytes.len() != size[0] as usize * size[1] as usize * bpp as usize {
839                continue;
840            }
841            let extent = wgpu::Extent3d {
842                width: size[0],
843                height: size[1],
844                depth_or_array_layers: 1,
845            };
846            let texture = device.create_texture(&wgpu::TextureDescriptor {
847                label: Some("egui-pop-viewport.tile"),
848                size: extent,
849                mip_level_count: 1,
850                sample_count: 1,
851                dimension: wgpu::TextureDimension::D2,
852                format: r.format,
853                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
854                view_formats: &[],
855            });
856            queue.write_texture(
857                texture.as_image_copy(),
858                &bytes,
859                wgpu::TexelCopyBufferLayout {
860                    offset: 0,
861                    bytes_per_row: Some(size[0] * bpp),
862                    rows_per_image: Some(size[1]),
863                },
864                extent,
865            );
866            copied.bytes += bytes.len() as u64;
867            copied.tiles += 1;
868            let bound = r.bind_tile(device, &texture, [0; 4]);
869            r.textures.insert(id, bound);
870        }
871        let mut q = self
872            .queue
873            .lock()
874            .unwrap_or_else(std::sync::PoisonError::into_inner);
875        q.copied.bytes += copied.bytes;
876        q.copied.tiles += copied.tiles;
877        q.copied.bound += copied.bound;
878    }
879
880    /// Writes the draws' uniforms for a target of `size` pixels whose
881    /// top left is `origin` in window pixels; `false` when there is
882    /// nothing to draw.
883    pub(crate) fn write_uniforms(
884        &self,
885        device: &wgpu::Device,
886        queue: &wgpu::Queue,
887        r: &mut Resources,
888        size: [f32; 2],
889        origin: [f32; 2],
890        target_is_srgb: bool,
891    ) -> bool {
892        if self.draws.is_empty() {
893            return false;
894        }
895        let stride = r.stride;
896        let needed = self.draws.len();
897        let grow = r.slots.get(&self.slot).is_none_or(|s| s.capacity < needed);
898        if grow {
899            let capacity = needed.next_power_of_two().max(16);
900            let buffer = device.create_buffer(&wgpu::BufferDescriptor {
901                label: Some("egui-pop-viewport.draws"),
902                size: stride * capacity as u64,
903                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
904                mapped_at_creation: false,
905            });
906            let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
907                label: Some("egui-pop-viewport.draws"),
908                layout: &r.uniform_layout,
909                entries: &[wgpu::BindGroupEntry {
910                    binding: 0,
911                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
912                        buffer: &buffer,
913                        offset: 0,
914                        size: wgpu::BufferSize::new(UNIFORM_SIZE),
915                    }),
916                }],
917            });
918            r.slots.insert(
919                self.slot,
920                Slot {
921                    buffer,
922                    group,
923                    capacity,
924                },
925            );
926        }
927        let Some(slot) = r.slots.get(&self.slot) else {
928            return false;
929        };
930        let r = &*r;
931        let mut bytes = vec![0u8; stride as usize * needed];
932        let [sw, sh] = size;
933        let m = &self.stage.matrix;
934        for (i, d) in self.draws.iter().enumerate() {
935            let layout = r.textures.get(&d.texture).map_or([0; 4], |b| b.layout);
936            let values: [f32; 28] = [
937                d.dst[0] - origin[0],
938                d.dst[1] - origin[1],
939                d.dst[2] - origin[0],
940                d.dst[3] - origin[1],
941                sw,
942                sh,
943                d.size[0] as f32,
944                d.size[1] as f32,
945                m[0][0],
946                m[0][1],
947                m[0][2],
948                0.0,
949                m[1][0],
950                m[1][1],
951                m[1][2],
952                0.0,
953                m[2][0],
954                m[2][1],
955                m[2][2],
956                0.0,
957                self.stage.clamp[0],
958                self.stage.clamp[1],
959                self.stage.transfer.code() as f32,
960                if target_is_srgb { 1.0 } else { 0.0 },
961                self.stage.white_nits,
962                0.0,
963                0.0,
964                0.0,
965            ];
966            let at = i * stride as usize;
967            for (k, v) in values.iter().enumerate() {
968                bytes[at + k * 4..at + k * 4 + 4].copy_from_slice(&v.to_le_bytes());
969            }
970            let at = at + values.len() * 4;
971            for (k, v) in layout.iter().enumerate() {
972                bytes[at + k * 4..at + k * 4 + 4].copy_from_slice(&v.to_le_bytes());
973            }
974        }
975        queue.write_buffer(&slot.buffer, 0, &bytes);
976        true
977    }
978
979    /// Records the draws with `pipelines` (the viewport set by the
980    /// caller): textures and buffers, each with its pipeline.
981    pub(crate) fn draw(
982        &self,
983        pass: &mut wgpu::RenderPass<'_>,
984        r: &Resources,
985        pipelines: &Pipelines,
986    ) {
987        let Some(slot) = r.slots.get(&self.slot) else {
988            return;
989        };
990        let mut current = None;
991        for (i, d) in self.draws.iter().enumerate() {
992            let Some(bound) = r.textures.get(&d.texture) else {
993                continue;
994            };
995            let pipeline = if bound.buffer {
996                match &pipelines.buffer {
997                    Some(p) => p,
998                    None => continue,
999                }
1000            } else {
1001                &pipelines.texture
1002            };
1003            if current != Some(bound.buffer) {
1004                pass.set_pipeline(pipeline);
1005                current = Some(bound.buffer);
1006            }
1007            pass.set_bind_group(0, &slot.group, &[(i as u64 * r.stride) as u32]);
1008            pass.set_bind_group(1, &bound.group, &[]);
1009            pass.draw(0..6, 0..1);
1010        }
1011    }
1012}
1013
1014impl egui_wgpu::CallbackTrait for TilePaint {
1015    fn prepare(
1016        &self,
1017        device: &wgpu::Device,
1018        queue: &wgpu::Queue,
1019        screen: &egui_wgpu::ScreenDescriptor,
1020        _encoder: &mut wgpu::CommandEncoder,
1021        resources: &mut egui_wgpu::CallbackResources,
1022    ) -> Vec<wgpu::CommandBuffer> {
1023        let Some(r) = resources.get_mut::<Resources>() else {
1024            return Vec::new();
1025        };
1026        self.sync_textures(device, queue, r);
1027        let [w, h] = screen.size_in_pixels;
1028        let srgb = r.target_is_srgb;
1029        self.write_uniforms(device, queue, r, [w as f32, h as f32], [0.0, 0.0], srgb);
1030        Vec::new()
1031    }
1032
1033    fn paint(
1034        &self,
1035        info: egui::PaintCallbackInfo,
1036        pass: &mut wgpu::RenderPass<'static>,
1037        resources: &egui_wgpu::CallbackResources,
1038    ) {
1039        let Some(r) = resources.get::<Resources>() else {
1040            return;
1041        };
1042        // Positions are in window pixels; the scissor keeps the clip.
1043        let [sw, sh] = info.screen_size_px;
1044        pass.set_viewport(0.0, 0.0, sw as f32, sh as f32, 0.0, 1.0);
1045        self.draw(pass, r, r.pipelines());
1046    }
1047}
1048
1049/// Sets the render device device tiles are checked against, as
1050/// [`install`] does, for tests without a render state.
1051#[cfg(test)]
1052pub(crate) fn set_render_device(ctx: &Context, device: &wgpu::Device) {
1053    RENDER.set(
1054        ctx,
1055        RenderDevice {
1056            device: device.clone(),
1057            buffers: true,
1058            storage_align: 256,
1059            max_binding: 1 << 27,
1060        },
1061    );
1062}
1063
1064#[cfg(test)]
1065mod tests {
1066    use super::{BUFFER, COMMON, TEXTURE, reads_fragment_storage};
1067
1068    /// WebGL 2 (downlevel flags and limits) reads no storage buffer in a
1069    /// fragment shader; a full WebGPU or native device does.
1070    #[test]
1071    fn fragment_storage_follows_the_flags_and_the_limits() {
1072        let webgl2 = wgpu::Limits::downlevel_webgl2_defaults();
1073        assert_eq!(webgl2.max_storage_buffers_per_shader_stage, 0);
1074        assert!(!reads_fragment_storage(
1075            wgpu::DownlevelFlags::empty(),
1076            &webgl2
1077        ));
1078        // The flag alone is not enough: the stage's limit must allow one.
1079        assert!(!reads_fragment_storage(
1080            wgpu::DownlevelFlags::FRAGMENT_STORAGE,
1081            &webgl2
1082        ));
1083        assert!(!reads_fragment_storage(
1084            wgpu::DownlevelFlags::empty(),
1085            &wgpu::Limits::default()
1086        ));
1087        assert!(reads_fragment_storage(
1088            wgpu::DownlevelFlags::all(),
1089            &wgpu::Limits::default()
1090        ));
1091    }
1092
1093    /// Each tile module, as `install` composes it, parses and validates
1094    /// with naga (what wgpu runs at shader creation), without a GPU.
1095    #[test]
1096    fn the_tile_shaders_parse_and_validate() {
1097        for (name, part) in [("texture", TEXTURE), ("buffer", BUFFER)] {
1098            let source = format!("{COMMON}{part}");
1099            let module = naga::front::wgsl::parse_str(&source)
1100                .unwrap_or_else(|e| panic!("{name}: {}", e.emit_to_string(&source)));
1101            naga::valid::Validator::new(
1102                naga::valid::ValidationFlags::all(),
1103                naga::valid::Capabilities::empty(),
1104            )
1105            .validate(&module)
1106            .unwrap_or_else(|e| panic!("{name}: {}", e.emit_to_string(&source)));
1107        }
1108    }
1109}