Skip to main content

webizen_render/wgpu_renderer/
renderer.rs

1//! `WgpuRenderer` state, VRAM residency admission, and target management.
2
3use super::pipelines::{ProjectorVertex, ScreenVertex};
4#[cfg(not(feature = "qualia"))]
5use super::vegetation_effects;
6use super::{
7    bounded_offscreen_extent, offscreen_rgba8_bytes, probe::capability_report_from_adapter, Camera,
8    ScreenPoint, WebGpuCapabilityReport,
9};
10
11#[cfg(feature = "qualia")]
12pub(super) type GraphicsReservation = qualia_core_db::gpu_context::VramReservation<'static>;
13#[cfg(not(feature = "qualia"))]
14pub(super) type GraphicsReservation = ();
15#[cfg(feature = "qualia")]
16pub(super) type GraphicsClass = qualia_core_db::gpu_context::VramResourceClass;
17#[cfg(not(feature = "qualia"))]
18#[derive(Clone, Copy)]
19pub(super) enum GraphicsClass {
20    Geometry,
21    FrameTarget,
22    UploadStaging,
23}
24
25#[derive(Default)]
26pub(super) struct RendererReservations {
27    pub(super) frame_target: Option<GraphicsReservation>,
28    pub(super) geometry: Option<GraphicsReservation>,
29}
30
31#[cfg(feature = "qualia")]
32pub(super) fn reserve_graphics_bytes(
33    class: GraphicsClass,
34    bytes: u64,
35    label: &str,
36) -> Result<GraphicsReservation, String> {
37    qualia_core_db::gpu_context::global_vram_ledger()
38        .try_reserve_graphics(class, bytes)
39        .map_err(|e| format!("webizen-render {label} admission failed: {e}"))
40}
41
42#[cfg(not(feature = "qualia"))]
43pub(super) fn reserve_graphics_bytes(
44    _class: GraphicsClass,
45    _bytes: u64,
46    _label: &str,
47) -> Result<GraphicsReservation, String> {
48    Ok(())
49}
50
51pub(super) fn vertex_buffer_residency_bytes(max_vertices: usize) -> Option<u64> {
52    (max_vertices as u64)
53        .checked_mul(std::mem::size_of::<ScreenVertex>() as u64)?
54        .checked_add(
55            (max_vertices as u64).checked_mul(std::mem::size_of::<ProjectorVertex>() as u64)?,
56        )
57}
58
59pub(super) fn reserve_vertex_buffer_residency() -> Result<GraphicsReservation, String> {
60    let bytes = vertex_buffer_residency_bytes(10_000)
61        .ok_or_else(|| "webizen-render vertex-buffer size overflow".to_string())?;
62    reserve_graphics_bytes(GraphicsClass::Geometry, bytes, "vertex buffer")
63}
64
65pub(super) fn reserve_offscreen_extent(
66    requested_width: u32,
67    requested_height: u32,
68) -> Result<(u32, u32, GraphicsReservation), String> {
69    #[allow(unused_mut)]
70    let (mut width, mut height) = bounded_offscreen_extent(requested_width, requested_height);
71    #[cfg(feature = "qualia")]
72    {
73        for _ in 0..33 {
74            let bytes = offscreen_rgba8_bytes(width, height)
75                .ok_or_else(|| "webizen-render target size overflow".to_string())?;
76            match reserve_graphics_bytes(GraphicsClass::FrameTarget, bytes, "offscreen target") {
77                Ok(reservation) => return Ok((width, height, reservation)),
78                Err(_) if width > 1 || height > 1 => {
79                    width = width.div_ceil(2);
80                    height = height.div_ceil(2);
81                }
82                Err(error) => return Err(error),
83            }
84        }
85        return Err("webizen-render could not admit a minimum offscreen target".into());
86    }
87    #[cfg(not(feature = "qualia"))]
88    {
89        let _ = offscreen_rgba8_bytes(width, height)
90            .ok_or_else(|| "webizen-render target size overflow".to_string())?;
91        Ok((width, height, ()))
92    }
93}
94
95/// Where the renderer draws each frame.
96pub(super) enum RenderTarget<'a> {
97    /// Windowed swapchain.
98    Surface {
99        surface: etalon::Surface<'a>,
100        config: etalon::SurfaceConfiguration,
101    },
102    /// Headless render-target texture with CPU readback.
103    Offscreen {
104        texture: etalon::Texture,
105        format: etalon::TextureFormat,
106        width: u32,
107        height: u32,
108    },
109}
110
111/// A single acquired frame's drawable view, plus (for surfaces) the swapchain
112/// texture that must be presented after submission.
113pub(super) enum Frame {
114    Surface {
115        texture: etalon::SurfaceTexture,
116        view: etalon::TextureView,
117    },
118    Offscreen {
119        view: etalon::TextureView,
120    },
121}
122
123impl Frame {
124    pub(super) fn view(&self) -> &etalon::TextureView {
125        match self {
126            Frame::Surface { view, .. } | Frame::Offscreen { view } => view,
127        }
128    }
129
130    /// Presents the swapchain texture. No-op for offscreen targets (their
131    /// contents persist in the texture and are read back on demand).
132    pub(super) fn present(self, queue: &etalon::Queue) {
133        if let Frame::Surface { texture, .. } = self {
134            queue.present(texture);
135        }
136    }
137}
138
139/// WGPU-based renderer implementation.
140pub struct WgpuRenderer<'a> {
141    pub(super) device: etalon::Device,
142    pub(super) queue: etalon::Queue,
143    pub(super) target: RenderTarget<'a>,
144    pub(super) capabilities: WebGpuCapabilityReport,
145    pub(super) requested_extent: (u32, u32),
146    pub(super) camera: Camera,
147    pub(super) viewport_size: (f64, f64),
148    pub(super) render_pipeline: etalon::RenderPipeline,
149    #[allow(dead_code)]
150    pub(super) projector_pipeline: Option<etalon::RenderPipeline>,
151    pub(super) vertex_buffer: etalon::Buffer,
152    #[allow(dead_code)]
153    pub(super) projector_vertex_buffer: etalon::Buffer,
154    pub(super) max_vertices: usize,
155    pub(super) reservations: RendererReservations,
156    pub(super) node_positions: Vec<(usize, ScreenPoint, f64)>,
157    #[cfg(not(feature = "qualia"))]
158    pub(super) ambient_config: AmbientConfig,
159    #[cfg(not(feature = "qualia"))]
160    pub(super) ambient_pipeline: Option<etalon::RenderPipeline>,
161    #[cfg(not(feature = "qualia"))]
162    pub(super) particle_buffer: Option<etalon::Buffer>,
163    #[cfg(not(feature = "qualia"))]
164    pub(super) ambient_uniform_buffer: Option<etalon::Buffer>,
165    #[cfg(not(feature = "qualia"))]
166    pub(super) telemetry_buffer: Option<etalon::Buffer>,
167    #[cfg(not(feature = "qualia"))]
168    pub(super) particle_count: usize,
169    #[cfg(not(feature = "qualia"))]
170    pub(super) ambient_effects: vegetation_effects::EffectPool,
171}
172
173impl<'a> WgpuRenderer<'a> {
174    /// Create a new WgpuRenderer that draws to a window surface.
175    pub async fn new(
176        surface: etalon::Surface<'a>,
177        width: u32,
178        height: u32,
179    ) -> Result<Self, String> {
180        let instance = etalon::Instance::default();
181
182        let (device, queue, adapter, capabilities) =
183            Self::request_device(&instance, Some(&surface)).await?;
184        let mut reservations = RendererReservations::default();
185        reservations.geometry = Some(reserve_vertex_buffer_residency()?);
186
187        let surface_caps = surface.get_capabilities(&adapter);
188        let surface_format = surface_caps
189            .formats
190            .iter()
191            .copied()
192            .find(|f| f.has_srgb_suffix())
193            .or_else(|| surface_caps.formats.first().copied())
194            .ok_or_else(|| "webizen-render surface has no supported formats".to_string())?;
195        let alpha_mode = surface_caps
196            .alpha_modes
197            .first()
198            .copied()
199            .ok_or_else(|| "webizen-render surface has no supported alpha modes".to_string())?;
200
201        let surface_config = etalon::SurfaceConfiguration {
202            usage: etalon::TextureUsages::RENDER_ATTACHMENT,
203            format: surface_format,
204            width,
205            height,
206            present_mode: etalon::PresentMode::Fifo,
207            alpha_mode,
208            color_space: etalon::SurfaceColorSpace::Auto,
209            view_formats: vec![],
210            desired_maximum_frame_latency: 2,
211        };
212
213        surface.configure(&device, &surface_config);
214
215        let render_pipeline = Self::create_render_pipeline(&device, surface_format);
216        let projector_pipeline = Self::create_projector_pipeline(&device, surface_format);
217
218        let (vertex_buffer, projector_vertex_buffer, max_vertices) =
219            Self::create_vertex_buffer(&device);
220
221        #[cfg(not(feature = "qualia"))]
222        let (
223            ambient_config,
224            ambient_pipeline,
225            particle_buffer,
226            ambient_uniform_buffer,
227            telemetry_buffer,
228            particle_count,
229            ambient_effects,
230        ) = Self::ambient_fields(&device, width, height);
231
232        Ok(Self {
233            device,
234            queue,
235            target: RenderTarget::Surface {
236                surface,
237                config: surface_config,
238            },
239            capabilities,
240            requested_extent: (width, height),
241            camera: Camera::default(),
242            viewport_size: (width as f64, height as f64),
243            render_pipeline,
244            projector_pipeline: Some(projector_pipeline),
245            vertex_buffer,
246            projector_vertex_buffer,
247            max_vertices,
248            reservations,
249            node_positions: Vec::new(),
250            #[cfg(not(feature = "qualia"))]
251            ambient_config,
252            #[cfg(not(feature = "qualia"))]
253            ambient_pipeline,
254            #[cfg(not(feature = "qualia"))]
255            particle_buffer,
256            #[cfg(not(feature = "qualia"))]
257            ambient_uniform_buffer,
258            #[cfg(not(feature = "qualia"))]
259            telemetry_buffer,
260            #[cfg(not(feature = "qualia"))]
261            particle_count,
262            #[cfg(not(feature = "qualia"))]
263            ambient_effects,
264        })
265    }
266
267    /// Create a headless renderer that draws to an offscreen texture.
268    pub async fn new_offscreen(width: u32, height: u32) -> Result<WgpuRenderer<'static>, String> {
269        let requested_extent = (width, height);
270        #[cfg(feature = "qualia")]
271        let (device, queue, capabilities) = {
272            let shared = qualia_core_db::gpu_context::try_shared_gpu().ok_or_else(|| {
273                "webizen-render adapter unavailable: shared GPU context is unavailable".to_string()
274            })?;
275            let capabilities =
276                capability_report_from_adapter(&shared.adapter, Some(&shared.device));
277            (shared.device.clone(), shared.queue.clone(), capabilities)
278        };
279
280        let (width, height, frame_target_reservation) = reserve_offscreen_extent(width, height)?;
281        let mut reservations = RendererReservations::default();
282        reservations.frame_target = Some(frame_target_reservation);
283        reservations.geometry = Some(reserve_vertex_buffer_residency()?);
284        #[cfg(not(feature = "qualia"))]
285        let (device, queue, capabilities) = {
286            let instance = etalon::Instance::default();
287            let (device, queue, _adapter, capabilities) =
288                Self::request_device(&instance, None).await?;
289            (device, queue, capabilities)
290        };
291
292        let format = etalon::TextureFormat::Rgba8Unorm;
293        let texture = Self::create_offscreen_texture(&device, format, width, height);
294
295        let render_pipeline = Self::create_render_pipeline(&device, format);
296        let projector_pipeline = Self::create_projector_pipeline(&device, format);
297
298        let (vertex_buffer, projector_vertex_buffer, max_vertices) =
299            Self::create_vertex_buffer(&device);
300
301        #[cfg(not(feature = "qualia"))]
302        let (
303            ambient_config,
304            ambient_pipeline,
305            particle_buffer,
306            ambient_uniform_buffer,
307            telemetry_buffer,
308            particle_count,
309            ambient_effects,
310        ) = Self::ambient_fields(&device, width, height);
311
312        Ok(WgpuRenderer {
313            device,
314            queue,
315            target: RenderTarget::Offscreen {
316                texture,
317                format,
318                width,
319                height,
320            },
321            capabilities,
322            requested_extent,
323            camera: Camera::default(),
324            viewport_size: (width as f64, height as f64),
325            render_pipeline,
326            projector_pipeline: Some(projector_pipeline),
327            vertex_buffer,
328            projector_vertex_buffer,
329            max_vertices,
330            reservations,
331            node_positions: Vec::new(),
332            #[cfg(not(feature = "qualia"))]
333            ambient_config,
334            #[cfg(not(feature = "qualia"))]
335            ambient_pipeline,
336            #[cfg(not(feature = "qualia"))]
337            particle_buffer,
338            #[cfg(not(feature = "qualia"))]
339            ambient_uniform_buffer,
340            #[cfg(not(feature = "qualia"))]
341            telemetry_buffer,
342            #[cfg(not(feature = "qualia"))]
343            particle_count,
344            #[cfg(not(feature = "qualia"))]
345            ambient_effects,
346        })
347    }
348
349    async fn request_device(
350        instance: &etalon::Instance,
351        compatible_surface: Option<&etalon::Surface<'_>>,
352    ) -> Result<
353        (
354            etalon::Device,
355            etalon::Queue,
356            etalon::Adapter,
357            WebGpuCapabilityReport,
358        ),
359        String,
360    > {
361        #[cfg(not(target_arch = "wasm32"))]
362        let power_preference = etalon::PowerPreference::HighPerformance;
363        #[cfg(target_arch = "wasm32")]
364        let power_preference = etalon::PowerPreference::LowPower;
365
366        let adapter = instance
367            .request_adapter(&etalon::RequestAdapterOptions {
368                power_preference,
369                compatible_surface,
370                force_fallback_adapter: false,
371                apply_limit_buckets: false,
372            })
373            .await
374            .map_err(|e| format!("webizen-render adapter unavailable: {e}"))?;
375
376        let (device, queue) = adapter
377            .request_device(&etalon::DeviceDescriptor {
378                label: Some("webizen-render-device"),
379                required_features: etalon::Features::empty(),
380                required_limits: etalon::Limits::downlevel_defaults(),
381                ..Default::default()
382            })
383            .await
384            .map_err(|e| format!("webizen-render device unavailable: {e}"))?;
385
386        let capabilities = capability_report_from_adapter(&adapter, Some(&device));
387        Ok((device, queue, adapter, capabilities))
388    }
389
390    pub(super) fn create_offscreen_texture(
391        device: &etalon::Device,
392        format: etalon::TextureFormat,
393        width: u32,
394        height: u32,
395    ) -> etalon::Texture {
396        device.create_texture(&etalon::TextureDescriptor {
397            label: Some("webizen-offscreen-target"),
398            size: etalon::Extent3d {
399                width,
400                height,
401                depth_or_array_layers: 1,
402            },
403            mip_level_count: 1,
404            sample_count: 1,
405            dimension: etalon::TextureDimension::D2,
406            format,
407            usage: etalon::TextureUsages::RENDER_ATTACHMENT | etalon::TextureUsages::COPY_SRC,
408            view_formats: &[],
409        })
410    }
411
412    pub(super) fn begin_frame(&self) -> Result<Frame, String> {
413        match &self.target {
414            RenderTarget::Surface { surface, .. } => {
415                let texture = match surface.get_current_texture() {
416                    etalon::CurrentSurfaceTexture::Success(texture)
417                    | etalon::CurrentSurfaceTexture::Suboptimal(texture) => texture,
418                    other => return Err(format!("Failed to get next surface texture: {other:?}")),
419                };
420                let view = texture
421                    .texture
422                    .create_view(&etalon::TextureViewDescriptor::default());
423                Ok(Frame::Surface { texture, view })
424            }
425            RenderTarget::Offscreen { texture, .. } => {
426                let view = texture.create_view(&etalon::TextureViewDescriptor::default());
427                Ok(Frame::Offscreen { view })
428            }
429        }
430    }
431
432    /// Return the bounded capability facts observed while constructing this renderer.
433    pub fn capabilities(&self) -> &WebGpuCapabilityReport {
434        &self.capabilities
435    }
436
437    /// Return the effective offscreen extent, or `None` for a surface target.
438    pub fn offscreen_extent(&self) -> Option<(u32, u32)> {
439        match &self.target {
440            RenderTarget::Offscreen { width, height, .. } => Some((*width, *height)),
441            RenderTarget::Surface { .. } => None,
442        }
443    }
444
445    /// Resize the render target.
446    pub fn resize(&mut self, width: u32, height: u32) {
447        if let Err(error) = self.try_resize(width, height) {
448            log::warn!("webizen-render resize retained previous target: {error}");
449        }
450    }
451
452    /// Resize while retaining the old target if the shared graphics budget
453    /// cannot admit the replacement. Offscreen targets may degrade by powers
454    /// of two and return their effective dimensions.
455    pub fn try_resize(&mut self, width: u32, height: u32) -> Result<(u32, u32), String> {
456        let requested_extent = (width, height);
457        let (width, height) = (width.max(1), height.max(1));
458        match &mut self.target {
459            RenderTarget::Surface { surface, config } => {
460                config.width = width;
461                config.height = height;
462                surface.configure(&self.device, config);
463                self.viewport_size = (width as f64, height as f64);
464                self.requested_extent = requested_extent;
465                Ok((width, height))
466            }
467            RenderTarget::Offscreen {
468                texture,
469                format,
470                width: current_width,
471                height: current_height,
472            } => {
473                let (width, height, reservation) = reserve_offscreen_extent(width, height)?;
474                if (*current_width, *current_height) == (width, height) {
475                    drop(reservation);
476                    self.requested_extent = requested_extent;
477                    return Ok((width, height));
478                }
479                let replacement =
480                    Self::create_offscreen_texture(&self.device, *format, width, height);
481                let retired_texture = std::mem::replace(texture, replacement);
482                *current_width = width;
483                *current_height = height;
484                let retired_reservation = self.reservations.frame_target.replace(reservation);
485                self.viewport_size = (width as f64, height as f64);
486                self.requested_extent = requested_extent;
487                let _ = self.device.poll(etalon::PollType::wait_indefinitely());
488                drop(retired_texture);
489                drop(retired_reservation);
490                Ok((width, height))
491            }
492        }
493    }
494}