Skip to main content

sim_engine/renderer/
mod.rs

1use std::{
2    borrow::Cow,
3    error::Error,
4    fmt,
5    ops::Range,
6    sync::Arc,
7    time::{Duration, Instant},
8};
9
10use crate::{
11    Camera2d, Circle, Color, ColorMap, DrawCommand, Fill, Line, LogicalScreenPosition,
12    LogicalViewport, ParticleInstance2d, PhysicalScreenPosition, Polyline, Rect, ScalarField,
13    Scene, ScreenClipRect, Shadow, ShapeStyle, Stroke, Vec2,
14};
15use config::select_surface_present_mode;
16
17const INITIAL_VERTEX_CAPACITY: usize = 4096;
18const CIRCLE_SEGMENTS: usize = 64;
19const ROUND_CAP_SEGMENTS: usize = 16;
20const CORNER_SEGMENTS: usize = 12;
21const PREFERRED_SAMPLE_COUNT: u32 = 4;
22
23#[repr(C)]
24#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
25struct Vertex {
26    world_position: [f32; 2],
27    depth: f32,
28    screen_offset: [f32; 2],
29    previous_direction: [f32; 2],
30    next_direction: [f32; 2],
31    normal_distance: f32,
32    color: [f32; 4],
33}
34
35#[repr(C)]
36#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
37struct DynamicGpu {
38    world_position: [f32; 2],
39    depth: f32,
40    color: [f32; 4],
41}
42
43#[repr(C)]
44#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
45struct CameraUniform {
46    camera_center: [f32; 4],
47    world_to_screen_x: [f32; 4],
48    world_to_screen_y: [f32; 4],
49    screen_to_clip: [f32; 4],
50}
51
52#[repr(C)]
53#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
54struct HeatmapUniform {
55    value_range: [f32; 4],
56    dimensions: [u32; 4],
57}
58
59#[repr(C)]
60#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
61struct CompositeUniform {
62    opacity: [f32; 4],
63}
64
65/// Scalar-field sampling mode used by heatmap rendering.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
67pub enum ScalarFieldSampling {
68    /// Select one exact source texel for each output fragment.
69    #[default]
70    Nearest,
71    /// Bilinearly interpolate neighboring source texels in shader math.
72    Linear,
73}
74
75impl ScalarFieldSampling {
76    fn shader_value(self) -> u32 {
77        match self {
78            Self::Nearest => 0,
79            Self::Linear => 1,
80        }
81    }
82}
83
84/// How a render target is combined with the presentation surface.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
86pub enum BlendMode {
87    /// Standard source-alpha compositing.
88    #[default]
89    Alpha,
90    /// Adds source light to the existing destination, useful for glow and trails.
91    Additive,
92    /// Replaces destination pixels with the source target.
93    Replace,
94}
95
96/// How a target-rendering pass initializes its destination pixels.
97#[derive(Debug, Clone, Copy, PartialEq)]
98pub enum RenderTargetLoad {
99    /// Preserve existing target pixels and blend new geometry over them.
100    Load,
101    /// Clear the target to a finite straight-alpha color before drawing.
102    Clear(Color),
103}
104
105#[derive(Debug, Clone, Copy)]
106struct GeometryExtents {
107    world_min: Vec2,
108    world_max: Vec2,
109    depth_min: f32,
110    depth_max: f32,
111    direction_min: Vec2,
112    direction_max: Vec2,
113    screen_offset_max_abs: Vec2,
114    normal_distance_max_abs: f32,
115    empty: bool,
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119struct ScissorRect {
120    x: u32,
121    y: u32,
122    width: u32,
123    height: u32,
124}
125
126#[derive(Debug, Clone, Copy)]
127struct ParticleDrawPreparation {
128    visible_count: usize,
129    upload: Duration,
130    camera_uniform_upload: Duration,
131}
132
133#[derive(Debug, Clone, PartialEq)]
134struct PreparedDrawBatch {
135    vertex_range: Range<u32>,
136    screen_clip: Option<ScreenClipRect>,
137}
138
139/// Outcome of converting accepted scene commands into GPU vertices.
140///
141/// A dropped command had finite source fields but produced no finite triangle
142/// vertices, usually because arithmetic overflowed while expanding geometry.
143/// Hosts can surface this separately from presentation success.
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
145pub struct TessellationStats {
146    command_count: usize,
147    rendered_command_count: usize,
148    dropped_command_count: usize,
149}
150
151impl TessellationStats {
152    /// Returns accepted source commands examined by the tessellator.
153    pub fn command_count(self) -> usize {
154        self.command_count
155    }
156
157    /// Returns source commands that emitted finite triangle vertices.
158    pub fn rendered_command_count(self) -> usize {
159        self.rendered_command_count
160    }
161
162    /// Returns source commands discarded because tessellation emitted no valid geometry.
163    pub fn dropped_command_count(self) -> usize {
164        self.dropped_command_count
165    }
166}
167
168impl Vertex {
169    const ATTRIBUTES: [wgpu::VertexAttribute; 7] = wgpu::vertex_attr_array![
170        0 => Float32x2,
171        1 => Float32,
172        2 => Float32x2,
173        3 => Float32x2,
174        4 => Float32x2,
175        5 => Float32,
176        6 => Float32x4
177    ];
178
179    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
180        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
181        step_mode: wgpu::VertexStepMode::Vertex,
182        attributes: &Self::ATTRIBUTES,
183    };
184
185    fn is_finite(self) -> bool {
186        self.world_position.iter().all(|value| value.is_finite())
187            && self.depth.is_finite()
188            && self.screen_offset.iter().all(|value| value.is_finite())
189            && self
190                .previous_direction
191                .iter()
192                .all(|value| value.is_finite())
193            && self.next_direction.iter().all(|value| value.is_finite())
194            && self.normal_distance.is_finite()
195            && self.color.iter().all(|value| value.is_finite())
196    }
197}
198
199impl DynamicGpu {
200    const ATTRIBUTES: [wgpu::VertexAttribute; 3] =
201        wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32, 2 => Float32x4];
202
203    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
204        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
205        step_mode: wgpu::VertexStepMode::Vertex,
206        attributes: &Self::ATTRIBUTES,
207    };
208}
209
210#[repr(C)]
211#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
212struct ParticleUnitVertex {
213    direction: [f32; 2],
214}
215
216impl ParticleUnitVertex {
217    const ATTRIBUTES: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![0 => Float32x2];
218
219    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
220        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
221        step_mode: wgpu::VertexStepMode::Vertex,
222        attributes: &Self::ATTRIBUTES,
223    };
224}
225
226#[repr(C)]
227#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
228struct ParticleGpu {
229    world_position: [f32; 2],
230    depth: f32,
231    radius: f32,
232    color: [f32; 4],
233}
234
235impl ParticleGpu {
236    const ATTRIBUTES: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![
237        1 => Float32x2,
238        2 => Float32,
239        3 => Float32,
240        4 => Float32x4
241    ];
242
243    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
244        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
245        step_mode: wgpu::VertexStepMode::Instance,
246        attributes: &Self::ATTRIBUTES,
247    };
248
249    fn screen_position(self, camera: CameraUniform) -> Vec2 {
250        let relative_x = self.world_position[0] - camera.camera_center[0];
251        let relative_y = self.world_position[1] - camera.camera_center[1];
252        Vec2::new(
253            camera.world_to_screen_x[0] * relative_x
254                + camera.world_to_screen_x[1] * relative_y
255                + camera.world_to_screen_x[2] * self.depth
256                + camera.world_to_screen_x[3],
257            camera.world_to_screen_y[0] * relative_x
258                + camera.world_to_screen_y[1] * relative_y
259                + camera.world_to_screen_y[2] * self.depth
260                + camera.world_to_screen_y[3],
261        )
262    }
263
264    fn is_safe_for(self, camera: CameraUniform) -> bool {
265        let relative_x = self.world_position[0] - camera.camera_center[0];
266        let relative_y = self.world_position[1] - camera.camera_center[1];
267        let screen = self.screen_position(camera);
268        let screen_x = screen.x;
269        let screen_y = screen.y;
270        let clip_x = screen_x * camera.screen_to_clip[0] + camera.screen_to_clip[2];
271        let clip_y = screen_y * camera.screen_to_clip[1] + camera.screen_to_clip[3];
272        relative_x.is_finite()
273            && relative_y.is_finite()
274            && screen_x.is_finite()
275            && screen_y.is_finite()
276            && (screen_x + self.radius).is_finite()
277            && (screen_x - self.radius).is_finite()
278            && (screen_y + self.radius).is_finite()
279            && (screen_y - self.radius).is_finite()
280            && clip_x.is_finite()
281            && clip_y.is_finite()
282    }
283
284    fn intersects_viewport(self, camera: CameraUniform, viewport: LogicalViewport) -> bool {
285        let screen = self.screen_position(camera);
286        screen.x + self.radius >= 0.0
287            && screen.x - self.radius <= viewport.width()
288            && screen.y + self.radius >= 0.0
289            && screen.y - self.radius <= viewport.height()
290    }
291}
292
293impl CameraUniform {
294    fn new(camera: Camera2d, viewport: LogicalViewport) -> Option<Self> {
295        let projection_cosine = camera.projection().tilt().cos();
296        let rotation_cosine = camera.rotation().cos();
297        let rotation_sine = camera.rotation().sin();
298        let zoom = camera.zoom();
299        let center = camera.center();
300        let projection_sine = camera.projection().tilt().sin();
301        let depth_scale = camera.projection().depth_scale();
302
303        let horizontal_x = zoom * rotation_cosine;
304        let horizontal_y = -zoom * rotation_sine * projection_cosine;
305        let vertical_x = -zoom * rotation_sine;
306        let vertical_y = -zoom * rotation_cosine * projection_cosine;
307        let horizontal_depth =
308            zoom * depth_scale * projection_sine * (rotation_cosine * 0.5 - rotation_sine);
309        let vertical_depth =
310            -zoom * depth_scale * projection_sine * (rotation_sine * 0.5 + rotation_cosine);
311
312        let uniform = Self {
313            camera_center: [center.x, center.y, 0.0, 0.0],
314            world_to_screen_x: [
315                horizontal_x,
316                horizontal_y,
317                horizontal_depth,
318                viewport.width() * 0.5,
319            ],
320            world_to_screen_y: [
321                vertical_x,
322                vertical_y,
323                vertical_depth,
324                viewport.height() * 0.5,
325            ],
326            screen_to_clip: [2.0 / viewport.width(), -2.0 / viewport.height(), -1.0, 1.0],
327        };
328        uniform.is_finite().then_some(uniform)
329    }
330
331    fn is_finite(self) -> bool {
332        self.camera_center
333            .iter()
334            .chain(self.world_to_screen_x.iter())
335            .chain(self.world_to_screen_y.iter())
336            .chain(self.screen_to_clip.iter())
337            .all(|value| value.is_finite())
338    }
339
340    #[cfg(test)]
341    fn world_to_screen(self, world: Vec2, depth: f32) -> Vec2 {
342        let relative = world - Vec2::new(self.camera_center[0], self.camera_center[1]);
343        Vec2::new(
344            self.world_to_screen_x[0] * relative.x
345                + self.world_to_screen_x[1] * relative.y
346                + self.world_to_screen_x[2] * depth
347                + self.world_to_screen_x[3],
348            self.world_to_screen_y[0] * relative.x
349                + self.world_to_screen_y[1] * relative.y
350                + self.world_to_screen_y[2] * depth
351                + self.world_to_screen_y[3],
352        )
353    }
354
355    #[cfg(test)]
356    fn direction_to_screen(self, direction: Vec2) -> Vec2 {
357        Vec2::new(
358            self.world_to_screen_x[0] * direction.x + self.world_to_screen_x[1] * direction.y,
359            self.world_to_screen_y[0] * direction.x + self.world_to_screen_y[1] * direction.y,
360        )
361    }
362}
363
364impl GeometryExtents {
365    fn empty(is_empty: bool) -> Self {
366        Self {
367            world_min: Vec2::splat(f32::INFINITY),
368            world_max: Vec2::splat(f32::NEG_INFINITY),
369            depth_min: f32::INFINITY,
370            depth_max: f32::NEG_INFINITY,
371            direction_min: Vec2::splat(f32::INFINITY),
372            direction_max: Vec2::splat(f32::NEG_INFINITY),
373            screen_offset_max_abs: Vec2::ZERO,
374            normal_distance_max_abs: 0.0,
375            empty: is_empty,
376        }
377    }
378
379    fn include(&mut self, vertex: Vertex) {
380        let world = Vec2::new(vertex.world_position[0], vertex.world_position[1]);
381        self.world_min.x = self.world_min.x.min(world.x);
382        self.world_min.y = self.world_min.y.min(world.y);
383        self.world_max.x = self.world_max.x.max(world.x);
384        self.world_max.y = self.world_max.y.max(world.y);
385        self.depth_min = self.depth_min.min(vertex.depth);
386        self.depth_max = self.depth_max.max(vertex.depth);
387
388        for direction in [vertex.previous_direction, vertex.next_direction] {
389            self.direction_min.x = self.direction_min.x.min(direction[0]);
390            self.direction_min.y = self.direction_min.y.min(direction[1]);
391            self.direction_max.x = self.direction_max.x.max(direction[0]);
392            self.direction_max.y = self.direction_max.y.max(direction[1]);
393        }
394
395        self.screen_offset_max_abs.x = self
396            .screen_offset_max_abs
397            .x
398            .max(vertex.screen_offset[0].abs());
399        self.screen_offset_max_abs.y = self
400            .screen_offset_max_abs
401            .y
402            .max(vertex.screen_offset[1].abs());
403        self.normal_distance_max_abs = self
404            .normal_distance_max_abs
405            .max(vertex.normal_distance.abs());
406    }
407
408    fn include_dynamic(&mut self, vertex: DynamicGpu) {
409        let world = Vec2::new(vertex.world_position[0], vertex.world_position[1]);
410        self.world_min.x = self.world_min.x.min(world.x);
411        self.world_min.y = self.world_min.y.min(world.y);
412        self.world_max.x = self.world_max.x.max(world.x);
413        self.world_max.y = self.world_max.y.max(world.y);
414        self.depth_min = self.depth_min.min(vertex.depth);
415        self.depth_max = self.depth_max.max(vertex.depth);
416        self.direction_min = Vec2::ZERO;
417        self.direction_max = Vec2::ZERO;
418    }
419
420    fn from_dynamic_vertices(vertices: &[DynamicGpu]) -> Self {
421        let mut extents = Self::empty(vertices.is_empty());
422        for vertex in vertices {
423            extents.include_dynamic(*vertex);
424        }
425        extents
426    }
427
428    fn from_vertices(vertices: &[Vertex]) -> Self {
429        let mut extents = Self::empty(vertices.is_empty());
430        for vertex in vertices {
431            extents.include(*vertex);
432        }
433
434        extents
435    }
436
437    fn is_safe_for(self, uniform: CameraUniform) -> bool {
438        if self.empty {
439            return true;
440        }
441
442        let center = Vec2::new(uniform.camera_center[0], uniform.camera_center[1]);
443        let world_horizontal = transformed_world_interval(
444            uniform.world_to_screen_x,
445            self.world_min,
446            self.world_max,
447            self.depth_min,
448            self.depth_max,
449            center,
450        );
451        let world_vertical = transformed_world_interval(
452            uniform.world_to_screen_y,
453            self.world_min,
454            self.world_max,
455            self.depth_min,
456            self.depth_max,
457            center,
458        );
459        let direction_horizontal = transformed_direction_interval(
460            uniform.world_to_screen_x,
461            self.direction_min,
462            self.direction_max,
463        );
464        let direction_vertical = transformed_direction_interval(
465            uniform.world_to_screen_y,
466            self.direction_min,
467            self.direction_max,
468        );
469        let maximum_miter = self.normal_distance_max_abs as f64 * 1_000.0;
470        let horizontal_limit = interval_max_abs(world_horizontal)
471            + self.screen_offset_max_abs.x as f64
472            + maximum_miter;
473        let vertical_limit =
474            interval_max_abs(world_vertical) + self.screen_offset_max_abs.y as f64 + maximum_miter;
475
476        [
477            world_horizontal.0,
478            world_horizontal.1,
479            world_vertical.0,
480            world_vertical.1,
481            direction_horizontal.0,
482            direction_horizontal.1,
483            direction_vertical.0,
484            direction_vertical.1,
485            horizontal_limit,
486            vertical_limit,
487        ]
488        .into_iter()
489        .all(|value| value.is_finite() && value.abs() <= f32::MAX as f64)
490    }
491}
492
493fn transformed_world_interval(
494    row: [f32; 4],
495    minimum: Vec2,
496    maximum: Vec2,
497    depth_minimum: f32,
498    depth_maximum: f32,
499    center: Vec2,
500) -> (f64, f64) {
501    let relative_minimum = minimum - center;
502    let relative_maximum = maximum - center;
503    let horizontal = interval_products(row[0], relative_minimum.x, relative_maximum.x);
504    let vertical = interval_products(row[1], relative_minimum.y, relative_maximum.y);
505    let depth = interval_products(row[2], depth_minimum, depth_maximum);
506    (
507        horizontal.0 + vertical.0 + depth.0 + row[3] as f64,
508        horizontal.1 + vertical.1 + depth.1 + row[3] as f64,
509    )
510}
511
512fn transformed_direction_interval(row: [f32; 4], minimum: Vec2, maximum: Vec2) -> (f64, f64) {
513    let horizontal = interval_products(row[0], minimum.x, maximum.x);
514    let vertical = interval_products(row[1], minimum.y, maximum.y);
515    (horizontal.0 + vertical.0, horizontal.1 + vertical.1)
516}
517
518fn interval_products(coefficient: f32, minimum: f32, maximum: f32) -> (f64, f64) {
519    let first = coefficient as f64 * minimum as f64;
520    let second = coefficient as f64 * maximum as f64;
521    (first.min(second), first.max(second))
522}
523
524fn interval_max_abs(interval: (f64, f64)) -> f64 {
525    interval.0.abs().max(interval.1.abs())
526}
527
528/// Result of attempting to draw a frame.
529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530pub enum RenderStatus {
531    /// Commands were submitted and the frame was presented.
532    Drawn,
533    /// The frame was skipped because the window surface was temporarily unavailable.
534    Skipped(RendererSurfaceStatus),
535}
536
537/// CPU-side durations measured while preparing and submitting one renderer frame.
538///
539/// These values do not measure GPU execution or the monitor scanout timestamp.
540/// FIFO presentation back-pressure normally appears in `surface_acquire` because
541/// `wgpu` blocks frame acquisition when the presentation queue is full.
542#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
543pub struct RendererFrameMetrics {
544    tessellation: Duration,
545    upload: Duration,
546    camera_uniform_upload: Duration,
547    surface_acquire: Duration,
548    encode_submit_present: Duration,
549    total_cpu: Duration,
550    geometry_reused: bool,
551    geometry_streamed: bool,
552    tessellation_stats: TessellationStats,
553}
554
555impl RendererFrameMetrics {
556    /// Returns CPU time spent validating and tessellating scene commands.
557    pub fn tessellation(self) -> Duration {
558        self.tessellation
559    }
560
561    /// Returns CPU time spent writing transient vertex data into the GPU buffer.
562    pub fn upload(self) -> Duration {
563        self.upload
564    }
565
566    /// Returns CPU time spent updating the small per-frame camera uniform.
567    pub fn camera_uniform_upload(self) -> Duration {
568        self.camera_uniform_upload
569    }
570
571    /// Returns CPU time spent acquiring the next presentation surface texture.
572    ///
573    /// In FIFO modes this includes queue back-pressure and is the closest CPU-side
574    /// approximation to VSync wait exposed by `wgpu`.
575    pub fn surface_acquire(self) -> Duration {
576        self.surface_acquire
577    }
578
579    /// Returns CPU time spent encoding, submitting, and dispatching present.
580    ///
581    /// Present dispatch does not mean the monitor has already scanned out the
582    /// frame; `wgpu` does not expose that timestamp here.
583    pub fn encode_submit_present(self) -> Duration {
584        self.encode_submit_present
585    }
586
587    /// Returns total CPU time inside the profiled render call.
588    pub fn total_cpu(self) -> Duration {
589        self.total_cpu
590    }
591
592    /// Returns whether this frame reused geometry from a [`PreparedScene`].
593    pub fn geometry_reused(self) -> bool {
594        self.geometry_reused
595    }
596
597    /// Returns whether this frame rendered geometry updated through [`DynamicMesh2d`].
598    pub fn geometry_streamed(self) -> bool {
599        self.geometry_streamed
600    }
601
602    /// Returns command-level tessellation results for this frame.
603    pub fn tessellation_stats(self) -> TessellationStats {
604        self.tessellation_stats
605    }
606}
607
608/// Status and CPU timing breakdown for one renderer frame.
609#[derive(Debug, Clone, Copy, PartialEq, Eq)]
610pub struct RenderReport {
611    status: RenderStatus,
612    metrics: RendererFrameMetrics,
613}
614
615impl RenderReport {
616    /// Returns whether the frame was drawn or skipped by the surface.
617    pub fn status(self) -> RenderStatus {
618        self.status
619    }
620
621    /// Returns CPU-side stage durations for the render call.
622    pub fn metrics(self) -> RendererFrameMetrics {
623        self.metrics
624    }
625}
626
627/// Recoverable or fatal state reported by the presentation surface.
628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
629pub enum RendererSurfaceStatus {
630    /// Acquiring the next frame timed out; try again on a later frame.
631    Timeout,
632    /// The surface is occluded or minimized; rendering can be skipped.
633    Occluded,
634    /// The surface configuration is stale; resizing or reconfiguring is needed.
635    Outdated,
636    /// The surface was lost and should be recreated by the host application.
637    Lost,
638    /// `wgpu` reported a validation error while acquiring the frame.
639    Validation,
640}
641
642/// Fatal failure while preparing or submitting one frame.
643#[derive(Debug, Clone, Copy, PartialEq, Eq)]
644pub enum RendererFrameError {
645    /// The presentation surface was lost or rejected frame acquisition.
646    Surface(RendererSurfaceStatus),
647    /// Camera and geometry are finite separately but overflow when transformed together.
648    InvalidGeometryTransform,
649    /// Tessellated geometry exceeds the active device's vertex-buffer limit.
650    GeometryCapacityTooLarge,
651}
652
653impl fmt::Display for RendererFrameError {
654    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
655        match self {
656            Self::Surface(status) => write!(formatter, "renderer surface failed: {status:?}"),
657            Self::InvalidGeometryTransform => {
658                write!(formatter, "camera and geometry overflow the GPU transform")
659            }
660            Self::GeometryCapacityTooLarge => {
661                write!(formatter, "geometry exceeds the GPU vertex-buffer limit")
662            }
663        }
664    }
665}
666
667impl Error for RendererFrameError {}
668
669/// Errors that can happen while creating the `wgpu` renderer.
670#[derive(Debug)]
671pub enum RendererInitError {
672    /// Surface creation failed for the provided window or canvas target.
673    CreateSurface(wgpu::CreateSurfaceError),
674    /// No compatible GPU adapter could be selected.
675    RequestAdapter(wgpu::RequestAdapterError),
676    /// A logical GPU device and queue could not be created.
677    RequestDevice(wgpu::RequestDeviceError),
678    /// The surface did not expose a usable default configuration.
679    NoSurfaceConfig,
680    /// The bounded previous-device quarantine is full.
681    RecoveryLimitReached {
682        /// Configured maximum number of quarantined logical devices.
683        limit: usize,
684    },
685}
686
687impl fmt::Display for RendererInitError {
688    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
689        match self {
690            Self::CreateSurface(error) => write!(formatter, "failed to create surface: {error}"),
691            Self::RequestAdapter(error) => write!(formatter, "failed to request adapter: {error}"),
692            Self::RequestDevice(error) => write!(formatter, "failed to request device: {error}"),
693            Self::NoSurfaceConfig => write!(formatter, "surface has no supported default config"),
694            Self::RecoveryLimitReached { limit } => write!(
695                formatter,
696                "device recovery limit reached with {limit} quarantined devices"
697            ),
698        }
699    }
700}
701
702impl Error for RendererInitError {}
703
704/// Invalid runtime or initialization configuration for [`WgpuRenderer`].
705#[derive(Debug, Clone, Copy, PartialEq)]
706pub enum RendererConfigurationError {
707    /// Logical-to-physical scale must produce finite logical dimensions for every supported surface.
708    InvalidScaleFactor {
709        /// Rejected physical pixels per logical screen pixel.
710        scale_factor: f64,
711    },
712    /// Previous-device quarantine must remain inside the supported bounded range.
713    InvalidRecoveryLimit {
714        /// Rejected maximum retained-device count.
715        limit: usize,
716    },
717}
718
719impl fmt::Display for RendererConfigurationError {
720    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
721        match self {
722            Self::InvalidScaleFactor { scale_factor } => write!(
723                formatter,
724                "renderer scale factor must be finite, positive, representable as f32, and keep a u32 surface finite in logical pixels, got {scale_factor}"
725            ),
726            Self::InvalidRecoveryLimit { limit } => write!(
727                formatter,
728                "renderer recovery quarantine must retain between 1 and 8 devices, got {limit}"
729            ),
730        }
731    }
732}
733
734impl Error for RendererConfigurationError {}
735
736/// Failure while converting between logical and physical screen coordinates.
737#[derive(Debug, Clone, Copy, PartialEq)]
738pub enum RendererCoordinateError {
739    /// The source position is non-finite or the scaled result cannot be represented as `f32`.
740    NonFiniteConversion,
741}
742
743impl fmt::Display for RendererCoordinateError {
744    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
745        write!(
746            formatter,
747            "screen coordinate conversion produced a non-finite result"
748        )
749    }
750}
751
752impl Error for RendererCoordinateError {}
753
754/// Failure while uploading or restoring immutable prepared-scene geometry.
755#[derive(Debug, Clone, Copy, PartialEq, Eq)]
756pub enum PreparedSceneError {
757    /// Tessellated geometry exceeds the active device's vertex-buffer limit.
758    CapacityTooLarge,
759}
760
761impl fmt::Display for PreparedSceneError {
762    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
763        match self {
764            Self::CapacityTooLarge => {
765                write!(
766                    formatter,
767                    "prepared scene exceeds the GPU vertex-buffer limit"
768                )
769            }
770        }
771    }
772}
773
774impl Error for PreparedSceneError {}
775
776/// Failure to draw geometry prepared by [`WgpuRenderer::prepare_scene`].
777#[derive(Debug, Clone, Copy, PartialEq, Eq)]
778pub enum PreparedSceneRenderError {
779    /// The prepared geometry belongs to a different renderer and GPU device.
780    RendererMismatch,
781    /// Frame rendering failed after prepared-scene ownership validation.
782    Frame(RendererFrameError),
783}
784
785impl fmt::Display for PreparedSceneRenderError {
786    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
787        match self {
788            Self::RendererMismatch => {
789                write!(formatter, "prepared scene belongs to a different renderer")
790            }
791            Self::Frame(error) => write!(formatter, "prepared frame failed: {error}"),
792        }
793    }
794}
795
796impl Error for PreparedSceneRenderError {}
797
798/// Immutable scene geometry tessellated and uploaded once for repeated drawing.
799///
800/// Camera movement, zoom, rotation, projection tilt, viewport resizing, and DPI
801/// changes do not invalidate prepared geometry. Shape, style, gradient, layer,
802/// or clip changes require preparing a replacement. A prepared scene can only be
803/// rendered by the [`WgpuRenderer`] that created it. Use
804/// [`WgpuRenderer::restore_prepared_scene`] to recreate its GPU buffer for a
805/// replacement renderer after device loss.
806pub struct PreparedScene {
807    renderer_identity: Arc<()>,
808    background: Color,
809    vertex_buffer: Arc<wgpu::Buffer>,
810    vertices: Arc<[Vertex]>,
811    command_count: usize,
812    vertex_count: usize,
813    geometry_extents: GeometryExtents,
814    draw_batches: Vec<PreparedDrawBatch>,
815    tessellation: TessellationStats,
816}
817
818/// One world-space vertex in a dynamic triangle-list mesh.
819///
820/// Dynamic meshes use plain filled triangles. Positions are measured in world
821/// units, `depth` uses the active camera projection, and colors are linear RGBA.
822#[derive(Debug, Clone, Copy, PartialEq)]
823pub struct DynamicVertex2d {
824    world_position: Vec2,
825    depth: f32,
826    color: Color,
827}
828
829impl DynamicVertex2d {
830    /// Builds a finite dynamic vertex.
831    pub fn new(world_position: Vec2, depth: f32, color: Color) -> Result<Self, DynamicMeshError> {
832        if !world_position.is_finite() || !depth.is_finite() || !color.is_normalized() {
833            return Err(DynamicMeshError::InvalidVertex);
834        }
835        Ok(Self {
836            world_position,
837            depth,
838            color,
839        })
840    }
841
842    /// Returns the world-space triangle position.
843    pub fn world_position(self) -> Vec2 {
844        self.world_position
845    }
846
847    /// Returns pseudo-depth in caller-defined units.
848    pub fn depth(self) -> f32 {
849        self.depth
850    }
851
852    /// Returns the linear RGBA vertex color.
853    pub fn color(self) -> Color {
854        self.color
855    }
856}
857
858/// Validation or ownership failure while changing a dynamic mesh.
859#[derive(Debug, Clone, Copy, PartialEq, Eq)]
860pub enum DynamicMeshError {
861    /// Triangle-list vertex counts must be divisible by three.
862    InvalidVertexCount,
863    /// A position, depth, or color contains NaN or infinity.
864    InvalidVertex,
865    /// A partial update lies outside the mesh's current vertex range.
866    UpdateRangeOutOfBounds,
867    /// The mesh belongs to a different renderer and GPU device.
868    RendererMismatch,
869    /// The mesh capacity exceeds the current device's vertex-buffer limit.
870    CapacityTooLarge,
871}
872
873impl fmt::Display for DynamicMeshError {
874    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
875        match self {
876            Self::InvalidVertexCount => write!(
877                formatter,
878                "dynamic mesh vertex count must be divisible by three"
879            ),
880            Self::InvalidVertex => write!(
881                formatter,
882                "dynamic mesh positions/depth must be finite and colors normalized"
883            ),
884            Self::UpdateRangeOutOfBounds => write!(
885                formatter,
886                "dynamic mesh update range is outside the current mesh"
887            ),
888            Self::RendererMismatch => {
889                write!(formatter, "dynamic mesh belongs to a different renderer")
890            }
891            Self::CapacityTooLarge => {
892                write!(
893                    formatter,
894                    "dynamic mesh exceeds the GPU vertex-buffer limit"
895                )
896            }
897        }
898    }
899}
900
901impl Error for DynamicMeshError {}
902
903/// Mutable GPU triangle-list geometry for high-frequency simulation visuals.
904///
905/// A mesh retains its CPU vertices for validation and recreates its GPU buffer
906/// only when a replacement exceeds its current capacity. Use
907/// [`WgpuRenderer::update_dynamic_mesh_range`] for in-place partial updates.
908pub struct DynamicMesh2d {
909    renderer_identity: Arc<()>,
910    vertex_buffer: Arc<wgpu::Buffer>,
911    vertices: Vec<DynamicGpu>,
912    vertex_capacity: usize,
913    geometry_extents: GeometryExtents,
914}
915
916impl DynamicMesh2d {
917    /// Returns the number of triangle-list vertices currently stored.
918    pub fn vertex_count(&self) -> usize {
919        self.vertices.len()
920    }
921
922    /// Returns the number of vertices that fit without reallocating its GPU buffer.
923    pub fn vertex_capacity(&self) -> usize {
924        self.vertex_capacity
925    }
926
927    /// Returns retained CPU memory used for validation and future updates.
928    pub fn recovery_memory_bytes(&self) -> usize {
929        self.vertices.len() * std::mem::size_of::<DynamicGpu>()
930    }
931}
932
933/// CPU-side outcome of one dynamic mesh update.
934#[derive(Debug, Clone, Copy, PartialEq, Eq)]
935pub struct DynamicMeshUpdateReport {
936    vertex_count: usize,
937    upload: Duration,
938    reallocated: bool,
939}
940
941impl DynamicMeshUpdateReport {
942    /// Returns the current triangle-list vertex count after the update.
943    pub fn vertex_count(self) -> usize {
944        self.vertex_count
945    }
946
947    /// Returns CPU time spent validating, allocating when needed, and writing GPU data.
948    pub fn upload(self) -> Duration {
949        self.upload
950    }
951
952    /// Returns whether this update grew and replaced the mesh GPU buffer.
953    pub fn reallocated(self) -> bool {
954        self.reallocated
955    }
956}
957
958/// Counts associated with one particle-field update or draw.
959#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
960pub struct ParticleStatistics {
961    submitted: usize,
962    visibility_checked: usize,
963    visible: usize,
964    culled: usize,
965    budget_limited: usize,
966    dropped: usize,
967    rendered: usize,
968}
969
970impl ParticleStatistics {
971    /// Returns instances supplied by the host.
972    pub fn submitted(self) -> usize {
973        self.submitted
974    }
975
976    /// Returns instances tested against the camera viewport this frame.
977    pub fn visibility_checked(self) -> usize {
978        self.visibility_checked
979    }
980
981    /// Returns checked instances that intersect the camera viewport.
982    pub fn visible(self) -> usize {
983        self.visible
984    }
985
986    /// Returns instances outside the current camera viewport.
987    pub fn culled(self) -> usize {
988        self.culled
989    }
990
991    /// Returns unchecked or camera-visible instances omitted by the render budget.
992    pub fn budget_limited(self) -> usize {
993        self.budget_limited
994    }
995
996    /// Returns instances rejected before GPU submission.
997    pub fn dropped(self) -> usize {
998        self.dropped
999    }
1000
1001    /// Returns instances submitted to the particle draw call.
1002    pub fn rendered(self) -> usize {
1003        self.rendered
1004    }
1005}
1006
1007/// Hard per-field limits that keep particle visualization from starving a host simulation.
1008#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1009pub struct ParticleRenderBudget {
1010    max_visible_instances: usize,
1011    max_gpu_bytes: usize,
1012    max_upload_bytes_per_frame: usize,
1013    max_visibility_checks_per_frame: usize,
1014}
1015
1016impl ParticleRenderBudget {
1017    /// No application-level cap beyond active-device allocation limits.
1018    pub const UNBOUNDED: Self = Self {
1019        max_visible_instances: usize::MAX,
1020        max_gpu_bytes: usize::MAX,
1021        max_upload_bytes_per_frame: usize::MAX,
1022        max_visibility_checks_per_frame: usize::MAX,
1023    };
1024
1025    /// Creates explicit visible-instance, GPU-memory, and per-frame upload caps.
1026    pub fn new(
1027        max_visible_instances: usize,
1028        max_gpu_bytes: usize,
1029        max_upload_bytes_per_frame: usize,
1030    ) -> Result<Self, ParticleBudgetError> {
1031        let minimum_bytes = std::mem::size_of::<ParticleGpu>();
1032        if max_visible_instances == 0
1033            || max_gpu_bytes < minimum_bytes
1034            || max_upload_bytes_per_frame < minimum_bytes
1035        {
1036            return Err(ParticleBudgetError::InvalidLimit);
1037        }
1038        Ok(Self {
1039            max_visible_instances,
1040            max_gpu_bytes,
1041            max_upload_bytes_per_frame,
1042            max_visibility_checks_per_frame: usize::MAX,
1043        })
1044    }
1045
1046    /// Caps camera visibility checks while sampling candidates uniformly across
1047    /// the retained field. The cap must fit the effective visible-instance cap.
1048    pub fn with_max_visibility_checks(
1049        mut self,
1050        max_visibility_checks_per_frame: usize,
1051    ) -> Result<Self, ParticleBudgetError> {
1052        if max_visibility_checks_per_frame < self.instance_limit() {
1053            return Err(ParticleBudgetError::InvalidLimit);
1054        }
1055        self.max_visibility_checks_per_frame = max_visibility_checks_per_frame;
1056        Ok(self)
1057    }
1058
1059    /// Returns the maximum camera-visible instances considered for drawing.
1060    pub const fn max_visible_instances(self) -> usize {
1061        self.max_visible_instances
1062    }
1063
1064    /// Returns the maximum particle instance-buffer allocation in bytes.
1065    pub const fn max_gpu_bytes(self) -> usize {
1066        self.max_gpu_bytes
1067    }
1068
1069    /// Returns the maximum particle bytes uploaded by one render call.
1070    pub const fn max_upload_bytes_per_frame(self) -> usize {
1071        self.max_upload_bytes_per_frame
1072    }
1073
1074    /// Returns the maximum retained instances checked against the viewport.
1075    pub const fn max_visibility_checks_per_frame(self) -> usize {
1076        self.max_visibility_checks_per_frame
1077    }
1078
1079    fn instance_limit(self) -> usize {
1080        self.max_visible_instances
1081            .min(self.max_gpu_bytes / std::mem::size_of::<ParticleGpu>())
1082            .min(self.max_upload_bytes_per_frame / std::mem::size_of::<ParticleGpu>())
1083    }
1084}
1085
1086impl Default for ParticleRenderBudget {
1087    fn default() -> Self {
1088        Self::UNBOUNDED
1089    }
1090}
1091
1092/// Invalid particle visualization resource budget.
1093#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1094pub enum ParticleBudgetError {
1095    /// Every enabled budget must fit at least one particle instance.
1096    InvalidLimit,
1097}
1098
1099impl fmt::Display for ParticleBudgetError {
1100    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1101        write!(
1102            formatter,
1103            "particle budget must fit at least one visible instance"
1104        )
1105    }
1106}
1107
1108impl Error for ParticleBudgetError {}
1109
1110/// Renderer-owned instanced particles for high-volume simulation visuals.
1111///
1112/// The field retains its validated CPU instances so it can be recreated after
1113/// device loss. Its GPU instance buffer grows only when a replacement exceeds
1114/// the current capacity.
1115pub struct ParticleField2d {
1116    renderer_identity: Arc<()>,
1117    instance_buffer: Arc<wgpu::Buffer>,
1118    instances: Vec<ParticleGpu>,
1119    visible_instances: Vec<ParticleGpu>,
1120    instance_capacity: usize,
1121    budget: ParticleRenderBudget,
1122    statistics: ParticleStatistics,
1123}
1124
1125impl ParticleField2d {
1126    /// Returns the number of particle instances currently stored.
1127    pub fn instance_count(&self) -> usize {
1128        self.instances.len()
1129    }
1130
1131    /// Returns the number of instances that fit without reallocating GPU memory.
1132    pub fn instance_capacity(&self) -> usize {
1133        self.instance_capacity
1134    }
1135
1136    /// Returns the most recent update or draw counts.
1137    pub fn statistics(&self) -> ParticleStatistics {
1138        self.statistics
1139    }
1140
1141    /// Returns the hard visualization budget applied by rendering.
1142    pub fn budget(&self) -> ParticleRenderBudget {
1143        self.budget
1144    }
1145
1146    /// Returns retained CPU memory used for recovery and validation.
1147    pub fn recovery_memory_bytes(&self) -> usize {
1148        self.instances.len() * std::mem::size_of::<ParticleGpu>()
1149    }
1150
1151    /// Returns currently reserved CPU bytes for retained and culled instance lists.
1152    pub fn cpu_allocation_bytes(&self) -> usize {
1153        self.instances
1154            .capacity()
1155            .saturating_add(self.visible_instances.capacity())
1156            .saturating_mul(std::mem::size_of::<ParticleGpu>())
1157    }
1158
1159    /// Returns allocated GPU instance-buffer bytes.
1160    pub fn gpu_allocation_bytes(&self) -> usize {
1161        self.instance_capacity
1162            .saturating_mul(std::mem::size_of::<ParticleGpu>())
1163    }
1164}
1165
1166/// Failure while creating or updating a [`ParticleField2d`].
1167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1168pub enum ParticleFieldError {
1169    /// An input instance violates the finite particle contract.
1170    InvalidInstance,
1171    /// A partial update lies outside the field's current instance range.
1172    UpdateRangeOutOfBounds,
1173    /// The field belongs to another renderer and GPU device.
1174    RendererMismatch,
1175    /// The instance capacity exceeds the current device's buffer limit.
1176    CapacityTooLarge,
1177}
1178
1179impl fmt::Display for ParticleFieldError {
1180    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1181        match self {
1182            Self::InvalidInstance => write!(formatter, "particle field instances must be valid"),
1183            Self::UpdateRangeOutOfBounds => {
1184                write!(
1185                    formatter,
1186                    "particle update range is outside the current field"
1187                )
1188            }
1189            Self::RendererMismatch => {
1190                write!(formatter, "particle field belongs to a different renderer")
1191            }
1192            Self::CapacityTooLarge => {
1193                write!(
1194                    formatter,
1195                    "particle field exceeds the GPU instance-buffer limit"
1196                )
1197            }
1198        }
1199    }
1200}
1201
1202impl Error for ParticleFieldError {}
1203
1204/// CPU-side outcome of one particle-field update.
1205#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1206pub struct ParticleFieldUpdateReport {
1207    statistics: ParticleStatistics,
1208    preparation: Duration,
1209    reallocated: bool,
1210}
1211
1212impl ParticleFieldUpdateReport {
1213    /// Returns submitted, visible, dropped, and rendered instance counts.
1214    pub fn statistics(self) -> ParticleStatistics {
1215        self.statistics
1216    }
1217
1218    /// Returns CPU time spent validating and retaining the new visual state.
1219    ///
1220    /// GPU upload is deferred until rendering, after camera culling has selected
1221    /// the compact visible set.
1222    pub fn preparation(self) -> Duration {
1223        self.preparation
1224    }
1225
1226    /// Backward-compatible alias for [`ParticleFieldUpdateReport::preparation`].
1227    #[deprecated(note = "particle GPU upload is deferred to render; use preparation()")]
1228    pub fn upload(self) -> Duration {
1229        self.preparation
1230    }
1231
1232    /// Returns whether this update grew and replaced the GPU instance buffer.
1233    pub fn reallocated(self) -> bool {
1234        self.reallocated
1235    }
1236}
1237
1238/// Failure while rendering a [`ParticleField2d`].
1239#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1240pub enum ParticleFieldRenderError {
1241    /// The field belongs to another renderer and GPU device.
1242    RendererMismatch,
1243    /// The clear color is not normalized linear RGBA.
1244    InvalidBackground,
1245    /// Camera transformation would produce non-finite particle geometry.
1246    InvalidGeometryTransform,
1247    /// Surface acquisition or presentation failed.
1248    Frame(RendererFrameError),
1249}
1250
1251impl fmt::Display for ParticleFieldRenderError {
1252    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1253        match self {
1254            Self::RendererMismatch => {
1255                write!(formatter, "particle field belongs to a different renderer")
1256            }
1257            Self::InvalidBackground => {
1258                write!(formatter, "particle field background must be normalized")
1259            }
1260            Self::InvalidGeometryTransform => {
1261                write!(formatter, "particle field geometry transform is invalid")
1262            }
1263            Self::Frame(error) => write!(formatter, "particle field frame failed: {error}"),
1264        }
1265    }
1266}
1267
1268impl Error for ParticleFieldRenderError {}
1269
1270/// Renderer-owned scalar texture retaining its validated source field.
1271pub struct ScalarFieldTexture {
1272    renderer_identity: Arc<()>,
1273    texture: wgpu::Texture,
1274    field: ScalarField,
1275}
1276
1277impl ScalarFieldTexture {
1278    /// Returns the current grid width in texels.
1279    pub fn width(&self) -> usize {
1280        self.field.width()
1281    }
1282
1283    /// Returns the current grid height in texels.
1284    pub fn height(&self) -> usize {
1285        self.field.height()
1286    }
1287
1288    /// Returns retained CPU scalar data used for recovery and uploads.
1289    pub fn field(&self) -> &ScalarField {
1290        &self.field
1291    }
1292
1293    /// Returns retained CPU scalar bytes used for device-loss recovery.
1294    pub fn recovery_memory_bytes(&self) -> usize {
1295        std::mem::size_of_val(self.field.values())
1296    }
1297
1298    /// Returns allocated `R32Float` texel bytes on the GPU.
1299    pub fn gpu_allocation_bytes(&self) -> usize {
1300        self.recovery_memory_bytes()
1301    }
1302}
1303
1304/// A renderer-owned offscreen color target in physical texture pixels.
1305///
1306/// Targets preserve GPU pixels only; a host must redraw them after device
1307/// recreation. Use the renderer's physical [`WgpuRenderer::size`] when a
1308/// target should match the presentation surface exactly.
1309pub struct RenderTarget2d {
1310    renderer_identity: Arc<()>,
1311    resource_identity: Arc<()>,
1312    _texture: wgpu::Texture,
1313    view: wgpu::TextureView,
1314    width: u32,
1315    height: u32,
1316    allocation_bytes: usize,
1317}
1318
1319/// A pair of offscreen targets used for bounded temporal accumulation.
1320///
1321/// Each accumulation retains a caller-selected amount of the previous frame
1322/// and then composites a distinct source target over it. The buffer owns no
1323/// domain state and can therefore serve particles, scalar fields, or any later
1324/// target-rendering producer.
1325pub struct TrailBuffer2d {
1326    renderer_identity: Arc<()>,
1327    front: RenderTarget2d,
1328    back: RenderTarget2d,
1329}
1330
1331impl TrailBuffer2d {
1332    /// Returns trail-buffer width in physical texture pixels.
1333    pub fn width(&self) -> u32 {
1334        self.front.width()
1335    }
1336
1337    /// Returns trail-buffer height in physical texture pixels.
1338    pub fn height(&self) -> u32 {
1339        self.front.height()
1340    }
1341
1342    /// Returns trail-buffer physical dimensions.
1343    pub fn size(&self) -> (u32, u32) {
1344        self.front.size()
1345    }
1346
1347    /// Returns total allocated bytes for both ping-pong textures.
1348    pub fn allocation_bytes(&self) -> usize {
1349        self.front
1350            .allocation_bytes()
1351            .saturating_add(self.back.allocation_bytes())
1352    }
1353}
1354
1355impl RenderTarget2d {
1356    /// Returns target width in physical texture pixels.
1357    pub fn width(&self) -> u32 {
1358        self.width
1359    }
1360
1361    /// Returns target height in physical texture pixels.
1362    pub fn height(&self) -> u32 {
1363        self.height
1364    }
1365
1366    /// Returns the physical texture dimensions.
1367    pub fn size(&self) -> (u32, u32) {
1368        (self.width, self.height)
1369    }
1370
1371    /// Returns the exact single-level GPU texture allocation implied by its format.
1372    pub fn allocation_bytes(&self) -> usize {
1373        self.allocation_bytes
1374    }
1375}
1376
1377/// Failure while creating or composing a [`RenderTarget2d`].
1378#[derive(Debug, Clone, Copy, PartialEq)]
1379pub enum RenderTargetError {
1380    /// Target dimensions must both be non-zero.
1381    ZeroDimension,
1382    /// Dimensions exceed the current device's supported target size or allocation range.
1383    DimensionsTooLarge,
1384    /// The target belongs to another renderer and GPU device.
1385    RendererMismatch,
1386    /// Opacity must be finite and within `0.0..=1.0`.
1387    InvalidOpacity,
1388    /// A temporal source must not be one of its destination ping-pong targets.
1389    SourceAliasesDestination,
1390    /// The destination clear color was not normalized linear RGBA.
1391    InvalidBackground,
1392    /// Surface acquisition or presentation failed.
1393    Frame(RendererFrameError),
1394}
1395
1396impl fmt::Display for RenderTargetError {
1397    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1398        match self {
1399            Self::ZeroDimension => write!(formatter, "render target dimensions must be non-zero"),
1400            Self::DimensionsTooLarge => {
1401                write!(formatter, "render target dimensions exceed device limits")
1402            }
1403            Self::RendererMismatch => {
1404                write!(formatter, "render target belongs to a different renderer")
1405            }
1406            Self::InvalidOpacity => write!(
1407                formatter,
1408                "render target opacity must be finite and in 0.0..=1.0"
1409            ),
1410            Self::SourceAliasesDestination => {
1411                write!(
1412                    formatter,
1413                    "trail source must be distinct from its destination targets"
1414                )
1415            }
1416            Self::InvalidBackground => {
1417                write!(formatter, "render target background must be normalized")
1418            }
1419            Self::Frame(error) => write!(formatter, "render target frame failed: {error}"),
1420        }
1421    }
1422}
1423
1424impl Error for RenderTargetError {}
1425
1426/// Failure while creating or updating a [`ScalarFieldTexture`].
1427#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1428pub enum ScalarFieldTextureError {
1429    /// The texture belongs to another renderer and GPU device.
1430    RendererMismatch,
1431    /// Grid dimensions exceed the addressable `wgpu` texture range.
1432    DimensionsTooLarge,
1433    /// A region does not fit inside the current scalar texture.
1434    UpdateRegionOutOfBounds,
1435    /// Region values did not match the region dimensions.
1436    InvalidUpdateValueCount,
1437    /// A region value was NaN or infinite.
1438    NonFiniteUpdateValue,
1439}
1440
1441impl fmt::Display for ScalarFieldTextureError {
1442    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1443        match self {
1444            Self::RendererMismatch => write!(
1445                formatter,
1446                "scalar field texture belongs to a different renderer"
1447            ),
1448            Self::DimensionsTooLarge => write!(
1449                formatter,
1450                "scalar field dimensions exceed GPU texture limits"
1451            ),
1452            Self::UpdateRegionOutOfBounds => {
1453                write!(formatter, "scalar texture update region is out of bounds")
1454            }
1455            Self::InvalidUpdateValueCount => {
1456                write!(
1457                    formatter,
1458                    "scalar texture update values do not match the region"
1459                )
1460            }
1461            Self::NonFiniteUpdateValue => {
1462                write!(formatter, "scalar texture update values must be finite")
1463            }
1464        }
1465    }
1466}
1467
1468impl Error for ScalarFieldTextureError {}
1469
1470/// Failure while rendering a scalar texture as a heatmap.
1471#[derive(Debug, Clone, Copy, PartialEq)]
1472pub enum ScalarFieldRenderError {
1473    /// The texture belongs to another renderer and GPU device.
1474    RendererMismatch,
1475    /// The scalar range was non-finite or did not have positive extent.
1476    InvalidValueRange {
1477        /// Lower bound supplied by the caller.
1478        minimum: f32,
1479        /// Upper bound supplied by the caller.
1480        maximum: f32,
1481    },
1482    /// The clear color is not normalized linear RGBA.
1483    InvalidBackground,
1484    /// Surface acquisition or presentation failed.
1485    Frame(RendererFrameError),
1486}
1487
1488impl fmt::Display for ScalarFieldRenderError {
1489    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1490        match self {
1491            Self::RendererMismatch => write!(
1492                formatter,
1493                "scalar field texture belongs to a different renderer"
1494            ),
1495            Self::InvalidValueRange { minimum, maximum } => {
1496                write!(formatter, "invalid scalar value range {minimum}..{maximum}")
1497            }
1498            Self::InvalidBackground => {
1499                write!(formatter, "scalar field background must be normalized")
1500            }
1501            Self::Frame(error) => write!(formatter, "scalar field frame failed: {error}"),
1502        }
1503    }
1504}
1505
1506impl Error for ScalarFieldRenderError {}
1507
1508/// CPU-side outcome of one scalar-field texture upload.
1509#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1510pub struct ScalarFieldUploadReport {
1511    upload: Duration,
1512    reallocated: bool,
1513}
1514
1515impl ScalarFieldUploadReport {
1516    /// Returns CPU time spent allocating when needed and enqueuing the upload.
1517    pub fn upload(self) -> Duration {
1518        self.upload
1519    }
1520
1521    /// Returns whether differing dimensions recreated the GPU texture.
1522    pub fn reallocated(self) -> bool {
1523        self.reallocated
1524    }
1525}
1526
1527/// Failure while rendering a [`DynamicMesh2d`].
1528#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1529pub enum DynamicMeshRenderError {
1530    /// The mesh belongs to another renderer and GPU device.
1531    RendererMismatch,
1532    /// The clear color is not normalized linear RGBA.
1533    InvalidBackground,
1534    /// Frame rendering failed after dynamic-mesh ownership validation.
1535    Frame(RendererFrameError),
1536}
1537
1538impl fmt::Display for DynamicMeshRenderError {
1539    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1540        match self {
1541            Self::RendererMismatch => {
1542                write!(formatter, "dynamic mesh belongs to a different renderer")
1543            }
1544            Self::InvalidBackground => {
1545                write!(formatter, "dynamic mesh background must be normalized")
1546            }
1547            Self::Frame(error) => write!(formatter, "dynamic mesh frame failed: {error}"),
1548        }
1549    }
1550}
1551
1552impl Error for DynamicMeshRenderError {}
1553
1554impl PreparedScene {
1555    /// Returns the number of accepted source scene commands.
1556    pub fn command_count(&self) -> usize {
1557        self.command_count
1558    }
1559
1560    /// Returns the number of triangle-list vertices stored in the GPU buffer.
1561    pub fn vertex_count(&self) -> usize {
1562        self.vertex_count
1563    }
1564
1565    /// Returns the number of clip-compatible draw batches.
1566    pub fn draw_batch_count(&self) -> usize {
1567        self.draw_batches.len()
1568    }
1569
1570    /// Returns retained CPU vertex bytes available for device-loss recovery.
1571    pub fn recovery_memory_bytes(&self) -> usize {
1572        self.vertices.len() * std::mem::size_of::<Vertex>()
1573    }
1574
1575    /// Returns command-level tessellation results captured during preparation.
1576    pub fn tessellation_stats(&self) -> TessellationStats {
1577        self.tessellation
1578    }
1579}
1580
1581/// `wgpu` backend that renders [`Scene`] commands into a presentation surface.
1582///
1583/// The renderer owns the GPU device, queue, surface, pipeline, and transient
1584/// vertex buffer. Window creation stays outside the library so each application
1585/// can choose its own windowing framework.
1586pub struct WgpuRenderer {
1587    renderer_identity: Arc<()>,
1588    _instance: wgpu::Instance,
1589    surface: wgpu::Surface<'static>,
1590    _adapter: wgpu::Adapter,
1591    device: wgpu::Device,
1592    queue: wgpu::Queue,
1593    config: wgpu::SurfaceConfiguration,
1594    requested_present_mode: RendererPresentMode,
1595    surface_present_mode: RendererSurfacePresentMode,
1596    scale_factor: f64,
1597    pipeline: wgpu::RenderPipeline,
1598    dynamic_pipeline: wgpu::RenderPipeline,
1599    particle_pipeline: wgpu::RenderPipeline,
1600    target_particle_pipeline: wgpu::RenderPipeline,
1601    heatmap_pipeline: wgpu::RenderPipeline,
1602    target_heatmap_pipeline: wgpu::RenderPipeline,
1603    composition_pipelines: CompositionPipelines,
1604    target_composition_pipelines: CompositionPipelines,
1605    mesh3d_renderer: Mesh3dRenderer,
1606    camera_uniform_buffer: wgpu::Buffer,
1607    camera_bind_group: wgpu::BindGroup,
1608    heatmap_uniform_buffer: wgpu::Buffer,
1609    heatmap_bind_group_layout: wgpu::BindGroupLayout,
1610    color_map_cache: Option<CachedColorMap>,
1611    vertex_buffer: Arc<wgpu::Buffer>,
1612    particle_unit_buffer: wgpu::Buffer,
1613    vertex_capacity: usize,
1614    multisample_target: Option<MultisampleTarget>,
1615    sample_count: u32,
1616    vertices: Vec<Vertex>,
1617    draw_batches: Vec<PreparedDrawBatch>,
1618    retired_devices: Vec<RetiredDevice>,
1619    max_quarantined_devices: usize,
1620}
1621
1622struct RetiredDevice {
1623    _adapter: wgpu::Adapter,
1624    _device: wgpu::Device,
1625    _queue: wgpu::Queue,
1626}
1627
1628impl WgpuRenderer {
1629    /// Creates a renderer for a window or canvas surface target.
1630    ///
1631    /// `width` and `height` are physical surface pixels. Zero sizes are clamped
1632    /// to one pixel because `wgpu` surfaces cannot be configured at zero size.
1633    /// This convenience constructor assumes a display scale factor of `1.0`;
1634    /// HiDPI hosts should use [`WgpuRenderer::new_with_options`].
1635    pub async fn new(
1636        surface_target: impl Into<wgpu::SurfaceTarget<'static>>,
1637        width: u32,
1638        height: u32,
1639    ) -> Result<Self, RendererInitError> {
1640        Self::new_with_options(
1641            surface_target,
1642            width,
1643            height,
1644            WgpuRendererOptions::default(),
1645        )
1646        .await
1647    }
1648
1649    /// Creates a renderer with explicit options.
1650    ///
1651    /// Use this when measuring renderer throughput or when the host application
1652    /// needs control over presentation behavior or display scale.
1653    pub async fn new_with_options(
1654        surface_target: impl Into<wgpu::SurfaceTarget<'static>>,
1655        width: u32,
1656        height: u32,
1657        options: WgpuRendererOptions,
1658    ) -> Result<Self, RendererInitError> {
1659        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
1660        let surface = instance
1661            .create_surface(surface_target)
1662            .map_err(RendererInitError::CreateSurface)?;
1663        let adapter = instance
1664            .request_adapter(&wgpu::RequestAdapterOptions {
1665                power_preference: wgpu::PowerPreference::HighPerformance,
1666                force_fallback_adapter: false,
1667                compatible_surface: Some(&surface),
1668                apply_limit_buckets: false,
1669            })
1670            .await
1671            .map_err(RendererInitError::RequestAdapter)?;
1672
1673        let (device, queue) = adapter
1674            .request_device(&wgpu::DeviceDescriptor {
1675                label: Some("sim-engine device"),
1676                required_features: wgpu::Features::empty(),
1677                required_limits: wgpu::Limits::default(),
1678                experimental_features: wgpu::ExperimentalFeatures::disabled(),
1679                memory_hints: wgpu::MemoryHints::Performance,
1680                trace: wgpu::Trace::Off,
1681            })
1682            .await
1683            .map_err(RendererInitError::RequestDevice)?;
1684
1685        let width = width.max(1);
1686        let height = height.max(1);
1687        let surface_capabilities = surface.get_capabilities(&adapter);
1688        let mut config = surface
1689            .get_default_config(&adapter, width, height)
1690            .ok_or(RendererInitError::NoSurfaceConfig)?;
1691        let surface_present_mode = select_surface_present_mode(
1692            options.present_mode(),
1693            &surface_capabilities.present_modes,
1694        );
1695        config.present_mode = surface_present_mode.to_wgpu();
1696        surface.configure(&device, &config);
1697
1698        let sample_count = preferred_sample_count(&adapter, config.format);
1699        let (
1700            pipeline,
1701            dynamic_pipeline,
1702            particle_pipeline,
1703            target_particle_pipeline,
1704            heatmap_pipeline,
1705            target_heatmap_pipeline,
1706            composition_pipelines,
1707            target_composition_pipelines,
1708            camera_uniform_buffer,
1709            camera_bind_group,
1710            heatmap_uniform_buffer,
1711            heatmap_bind_group_layout,
1712        ) = create_pipeline(&device, config.format, sample_count);
1713        let vertex_buffer = Arc::new(create_vertex_buffer(&device, INITIAL_VERTEX_CAPACITY));
1714        let particle_unit_buffer = create_particle_unit_buffer(&device, &queue);
1715        let multisample_target = create_multisample_target(&device, &config, sample_count);
1716        let mesh3d_renderer = Mesh3dRenderer::new(&device, config.format);
1717
1718        Ok(Self {
1719            renderer_identity: Arc::new(()),
1720            _instance: instance,
1721            surface,
1722            _adapter: adapter,
1723            device,
1724            queue,
1725            config,
1726            requested_present_mode: options.present_mode(),
1727            surface_present_mode,
1728            scale_factor: options.scale_factor(),
1729            pipeline,
1730            dynamic_pipeline,
1731            particle_pipeline,
1732            target_particle_pipeline,
1733            heatmap_pipeline,
1734            target_heatmap_pipeline,
1735            composition_pipelines,
1736            target_composition_pipelines,
1737            mesh3d_renderer,
1738            camera_uniform_buffer,
1739            camera_bind_group,
1740            heatmap_uniform_buffer,
1741            heatmap_bind_group_layout,
1742            color_map_cache: None,
1743            vertex_buffer,
1744            particle_unit_buffer,
1745            vertex_capacity: INITIAL_VERTEX_CAPACITY,
1746            multisample_target,
1747            sample_count,
1748            vertices: Vec::with_capacity(INITIAL_VERTEX_CAPACITY),
1749            draw_batches: Vec::new(),
1750            retired_devices: Vec::new(),
1751            max_quarantined_devices: options.max_quarantined_devices(),
1752        })
1753    }
1754
1755    /// Returns the configured surface size in physical pixels.
1756    pub fn size(&self) -> (u32, u32) {
1757        (self.config.width, self.config.height)
1758    }
1759
1760    /// Returns the render viewport size in logical screen pixels.
1761    ///
1762    /// Scene clipping, stroke widths, shadows, and camera zoom use this logical
1763    /// coordinate space so their visual size remains stable across display DPI.
1764    pub fn logical_size(&self) -> (f32, f32) {
1765        let scale_factor = self.scale_factor as f32;
1766        (
1767            self.config.width as f32 / scale_factor,
1768            self.config.height as f32 / scale_factor,
1769        )
1770    }
1771
1772    /// Returns the current camera viewport in logical screen pixels.
1773    pub fn logical_viewport(&self) -> Result<LogicalViewport, crate::LogicalViewportError> {
1774        let (width, height) = self.logical_size();
1775        LogicalViewport::new(width, height)
1776    }
1777
1778    /// Converts a physical surface position into logical screen pixels.
1779    pub fn physical_to_logical_screen(
1780        &self,
1781        position: PhysicalScreenPosition,
1782    ) -> Result<LogicalScreenPosition, RendererCoordinateError> {
1783        physical_to_logical_screen(position, self.scale_factor as f32)
1784    }
1785
1786    /// Converts a logical screen position into physical surface pixels.
1787    pub fn logical_to_physical_screen(
1788        &self,
1789        position: LogicalScreenPosition,
1790    ) -> Result<PhysicalScreenPosition, RendererCoordinateError> {
1791        logical_to_physical_screen(position, self.scale_factor as f32)
1792    }
1793
1794    /// Returns physical surface pixels per logical screen pixel.
1795    pub fn scale_factor(&self) -> f64 {
1796        self.scale_factor
1797    }
1798
1799    /// Returns the concrete presentation mode selected for the active surface.
1800    ///
1801    /// `RendererPresentMode::NoVsync` prefers Immediate, then Mailbox, then
1802    /// FIFO. This method reveals which supported fallback was configured. The
1803    /// desktop compositor may still pace host redraw callbacks independently.
1804    pub fn surface_present_mode(&self) -> RendererSurfacePresentMode {
1805        self.surface_present_mode
1806    }
1807
1808    /// Returns previous logical devices retained for safe native-driver teardown.
1809    pub fn quarantined_device_count(&self) -> usize {
1810        self.retired_devices.len()
1811    }
1812
1813    /// Returns the configured maximum previous-device quarantine size.
1814    pub fn max_quarantined_device_count(&self) -> usize {
1815        self.max_quarantined_devices
1816    }
1817
1818    /// Returns successful recoveries available before the bounded quarantine is full.
1819    pub fn remaining_device_recoveries(&self) -> usize {
1820        self.max_quarantined_devices
1821            .saturating_sub(self.retired_devices.len())
1822    }
1823
1824    /// Blocks until all previously submitted GPU work has completed.
1825    ///
1826    /// This is intended for diagnostic throughput measurements, readback, and
1827    /// controlled resource teardown. Calling it in an interactive frame loop
1828    /// defeats normal CPU/GPU pipelining.
1829    pub fn wait_for_gpu_idle(&self) -> Result<(), wgpu::PollError> {
1830        self.device
1831            .poll(wgpu::PollType::wait_indefinitely())
1832            .map(|_| ())
1833    }
1834
1835    /// Replaces display scale without changing physical surface dimensions.
1836    ///
1837    /// Invalid values return an error and leave the current scale unchanged.
1838    pub fn set_scale_factor(
1839        &mut self,
1840        scale_factor: f64,
1841    ) -> Result<(), RendererConfigurationError> {
1842        validate_scale_factor(scale_factor)?;
1843        self.scale_factor = scale_factor;
1844        Ok(())
1845    }
1846
1847    /// Reconfigures the surface after a host window resize.
1848    ///
1849    /// Zero width or height is ignored because minimized windows often report
1850    /// zero size and `wgpu` cannot configure a zero-sized surface.
1851    pub fn resize(&mut self, width: u32, height: u32) {
1852        if width == 0 || height == 0 {
1853            return;
1854        }
1855
1856        self.config.width = width;
1857        self.config.height = height;
1858        self.surface.configure(&self.device, &self.config);
1859        self.multisample_target =
1860            create_multisample_target(&self.device, &self.config, self.sample_count);
1861    }
1862
1863    /// Reconfigures physical surface size and logical-to-physical display scale.
1864    ///
1865    /// Invalid scale returns an error without changing either value. Zero
1866    /// physical dimensions update the scale but leave the minimized surface
1867    /// configuration unchanged.
1868    pub fn resize_with_scale_factor(
1869        &mut self,
1870        width: u32,
1871        height: u32,
1872        scale_factor: f64,
1873    ) -> Result<(), RendererConfigurationError> {
1874        validate_scale_factor(scale_factor)?;
1875        self.scale_factor = scale_factor;
1876        self.resize(width, height);
1877        Ok(())
1878    }
1879
1880    /// Draws a scene using the supplied camera.
1881    ///
1882    /// Scene positions and sizes are in world units unless a style explicitly
1883    /// says logical screen pixels. The renderer converts world coordinates to
1884    /// logical screen coordinates through [`Camera2d`], then to normalized device
1885    /// coordinates for `wgpu`. Scissor rectangles are converted to physical
1886    /// surface pixels at the final backend boundary.
1887    pub fn render(
1888        &mut self,
1889        scene: &Scene,
1890        camera: &Camera2d,
1891    ) -> Result<RenderStatus, RendererFrameError> {
1892        self.render_with_metrics(scene, camera)
1893            .map(RenderReport::status)
1894    }
1895
1896    /// Draws a scene and returns a CPU-side timing breakdown.
1897    ///
1898    /// Metrics separate tessellation, buffer upload, surface acquisition, and
1899    /// encode/submit/present dispatch. They do not measure GPU completion or the
1900    /// monitor scanout timestamp. Use this for diagnostics; [`WgpuRenderer::render`]
1901    /// is the simpler equivalent when stage timings are not needed.
1902    pub fn render_with_metrics(
1903        &mut self,
1904        scene: &Scene,
1905        camera: &Camera2d,
1906    ) -> Result<RenderReport, RendererFrameError> {
1907        let frame_started_at = Instant::now();
1908        let tessellation_started_at = Instant::now();
1909        self.vertices.clear();
1910        self.draw_batches.clear();
1911        let tessellation_stats =
1912            tessellate_scene(scene, &mut self.vertices, &mut self.draw_batches);
1913        self.ensure_vertex_capacity(self.vertices.len())?;
1914        let tessellation = tessellation_started_at.elapsed();
1915
1916        let upload_started_at = Instant::now();
1917        if !self.vertices.is_empty() {
1918            self.queue
1919                .write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(&self.vertices));
1920        }
1921        let upload = upload_started_at.elapsed();
1922
1923        let vertex_buffer = Arc::clone(&self.vertex_buffer);
1924        let draw_batches = std::mem::take(&mut self.draw_batches);
1925        let geometry_extents = GeometryExtents::from_vertices(&self.vertices);
1926        let result = self.draw_geometry(
1927            scene.background(),
1928            &vertex_buffer,
1929            self.vertices.len(),
1930            geometry_extents,
1931            &draw_batches,
1932            *camera,
1933            tessellation,
1934            upload,
1935            false,
1936            false,
1937            tessellation_stats,
1938            frame_started_at,
1939        );
1940        self.draw_batches = draw_batches;
1941        result
1942    }
1943
1944    /// Tessellates a scene once and uploads immutable geometry to a dedicated GPU buffer.
1945    ///
1946    /// Preparing is appropriate for geometry that will be drawn repeatedly while
1947    /// only the camera or target dimensions change. Any shape, style, gradient,
1948    /// ordering, or clipping change requires preparing a replacement scene.
1949    pub fn prepare_scene(&self, scene: &Scene) -> Result<PreparedScene, PreparedSceneError> {
1950        prepare_scene_resources(
1951            &self.device,
1952            &self.queue,
1953            Arc::clone(&self.renderer_identity),
1954            scene,
1955        )
1956    }
1957
1958    /// Recreates prepared GPU resources on this renderer from a retained CPU snapshot.
1959    ///
1960    /// This supports renderer recreation after device loss without requiring the
1961    /// original high-level [`Scene`]. The returned snapshot belongs to this renderer.
1962    pub fn restore_prepared_scene(
1963        &self,
1964        source: &PreparedScene,
1965    ) -> Result<PreparedScene, PreparedSceneError> {
1966        restore_prepared_scene_resources(
1967            &self.device,
1968            &self.queue,
1969            Arc::clone(&self.renderer_identity),
1970            source,
1971        )
1972    }
1973
1974    /// Recreates a dynamic mesh on this renderer from its retained CPU vertices.
1975    ///
1976    /// Use this after recreating a renderer following device loss. The returned
1977    /// mesh belongs to this renderer and preserves the source mesh's capacity so
1978    /// subsequent updates retain the same allocation behavior.
1979    pub fn restore_dynamic_mesh(
1980        &self,
1981        source: &DynamicMesh2d,
1982    ) -> Result<DynamicMesh2d, DynamicMeshError> {
1983        restore_dynamic_mesh_resources(
1984            &self.device,
1985            &self.queue,
1986            Arc::clone(&self.renderer_identity),
1987            source,
1988        )
1989    }
1990
1991    /// Creates mutable triangle-list geometry for a frequently changing visual.
1992    ///
1993    /// The vertex count must be divisible by three. The mesh is owned by this
1994    /// renderer and may only be updated or drawn through it.
1995    pub fn create_dynamic_mesh(
1996        &self,
1997        vertices: &[DynamicVertex2d],
1998    ) -> Result<DynamicMesh2d, DynamicMeshError> {
1999        let vertices = dynamic_vertices_to_gpu(vertices)?;
2000        let vertex_capacity = dynamic_vertex_capacity(vertices.len())
2001            .filter(|capacity| buffer_capacity_fits::<DynamicGpu>(&self.device, *capacity))
2002            .ok_or(DynamicMeshError::CapacityTooLarge)?;
2003        let vertex_buffer = Arc::new(create_dynamic_vertex_buffer(&self.device, vertex_capacity));
2004        if !vertices.is_empty() {
2005            self.queue
2006                .write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(&vertices));
2007        }
2008        Ok(DynamicMesh2d {
2009            renderer_identity: Arc::clone(&self.renderer_identity),
2010            geometry_extents: GeometryExtents::from_dynamic_vertices(&vertices),
2011            vertex_buffer,
2012            vertices,
2013            vertex_capacity,
2014        })
2015    }
2016
2017    /// Replaces all dynamic mesh vertices, growing GPU capacity only when needed.
2018    pub fn update_dynamic_mesh(
2019        &self,
2020        mesh: &mut DynamicMesh2d,
2021        vertices: &[DynamicVertex2d],
2022    ) -> Result<(), DynamicMeshError> {
2023        self.update_dynamic_mesh_with_metrics(mesh, vertices)
2024            .map(|_| ())
2025    }
2026
2027    /// Replaces all dynamic mesh vertices and returns CPU-side update metrics.
2028    pub fn update_dynamic_mesh_with_metrics(
2029        &self,
2030        mesh: &mut DynamicMesh2d,
2031        vertices: &[DynamicVertex2d],
2032    ) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
2033        let update_started_at = Instant::now();
2034        self.validate_dynamic_mesh(mesh)?;
2035        validate_dynamic_vertices(vertices)?;
2036        let reallocated = vertices.len() > mesh.vertex_capacity;
2037        if reallocated {
2038            mesh.vertex_capacity = dynamic_vertex_capacity(vertices.len())
2039                .filter(|capacity| buffer_capacity_fits::<DynamicGpu>(&self.device, *capacity))
2040                .ok_or(DynamicMeshError::CapacityTooLarge)?;
2041            mesh.vertex_buffer = Arc::new(create_dynamic_vertex_buffer(
2042                &self.device,
2043                mesh.vertex_capacity,
2044            ));
2045        }
2046        mesh.vertices.clear();
2047        mesh.vertices.reserve(vertices.len());
2048        let mut geometry_extents = GeometryExtents::empty(vertices.is_empty());
2049        for vertex in vertices.iter().copied() {
2050            let vertex = dynamic_vertex_to_gpu(vertex);
2051            geometry_extents.include_dynamic(vertex);
2052            mesh.vertices.push(vertex);
2053        }
2054        if !mesh.vertices.is_empty() {
2055            self.queue
2056                .write_buffer(&mesh.vertex_buffer, 0, bytemuck::cast_slice(&mesh.vertices));
2057        }
2058        mesh.geometry_extents = geometry_extents;
2059        Ok(DynamicMeshUpdateReport {
2060            vertex_count: mesh.vertices.len(),
2061            upload: update_started_at.elapsed(),
2062            reallocated,
2063        })
2064    }
2065
2066    /// Replaces a contiguous vertex range without reallocating the mesh buffer.
2067    ///
2068    /// The range must stay inside the current triangle list and its length must
2069    /// preserve triangle alignment, so callers cannot create partial triangles.
2070    pub fn update_dynamic_mesh_range(
2071        &self,
2072        mesh: &mut DynamicMesh2d,
2073        first_vertex: usize,
2074        vertices: &[DynamicVertex2d],
2075    ) -> Result<(), DynamicMeshError> {
2076        self.update_dynamic_mesh_range_with_metrics(mesh, first_vertex, vertices)
2077            .map(|_| ())
2078    }
2079
2080    /// Replaces a triangle-aligned range and returns CPU-side update metrics.
2081    pub fn update_dynamic_mesh_range_with_metrics(
2082        &self,
2083        mesh: &mut DynamicMesh2d,
2084        first_vertex: usize,
2085        vertices: &[DynamicVertex2d],
2086    ) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
2087        let update_started_at = Instant::now();
2088        self.validate_dynamic_mesh(mesh)?;
2089        let end = first_vertex
2090            .checked_add(vertices.len())
2091            .ok_or(DynamicMeshError::UpdateRangeOutOfBounds)?;
2092        if !first_vertex.is_multiple_of(3)
2093            || !vertices.len().is_multiple_of(3)
2094            || end > mesh.vertices.len()
2095        {
2096            return Err(DynamicMeshError::UpdateRangeOutOfBounds);
2097        }
2098        let vertices = dynamic_vertices_to_gpu(vertices)?;
2099        if !vertices.is_empty() {
2100            let offset = (first_vertex * std::mem::size_of::<DynamicGpu>()) as wgpu::BufferAddress;
2101            self.queue
2102                .write_buffer(&mesh.vertex_buffer, offset, bytemuck::cast_slice(&vertices));
2103            mesh.vertices[first_vertex..end].copy_from_slice(&vertices);
2104            mesh.geometry_extents = GeometryExtents::from_dynamic_vertices(&mesh.vertices);
2105        }
2106        Ok(DynamicMeshUpdateReport {
2107            vertex_count: mesh.vertices.len(),
2108            upload: update_started_at.elapsed(),
2109            reallocated: false,
2110        })
2111    }
2112
2113    /// Draws dynamic triangle-list geometry with a normalized clear color.
2114    pub fn render_dynamic_mesh(
2115        &mut self,
2116        mesh: &DynamicMesh2d,
2117        background: Color,
2118        camera: &Camera2d,
2119    ) -> Result<RenderStatus, DynamicMeshRenderError> {
2120        self.render_dynamic_mesh_with_metrics(mesh, background, camera)
2121            .map(RenderReport::status)
2122    }
2123
2124    /// Draws dynamic triangle-list geometry and returns per-frame CPU metrics.
2125    pub fn render_dynamic_mesh_with_metrics(
2126        &mut self,
2127        mesh: &DynamicMesh2d,
2128        background: Color,
2129        camera: &Camera2d,
2130    ) -> Result<RenderReport, DynamicMeshRenderError> {
2131        self.validate_dynamic_mesh(mesh)
2132            .map_err(|_| DynamicMeshRenderError::RendererMismatch)?;
2133        if !background.is_normalized() {
2134            return Err(DynamicMeshRenderError::InvalidBackground);
2135        }
2136        let draw_batches = (!mesh.vertices.is_empty()).then_some(PreparedDrawBatch {
2137            vertex_range: 0..mesh.vertices.len() as u32,
2138            screen_clip: None,
2139        });
2140        self.draw_geometry(
2141            background,
2142            &mesh.vertex_buffer,
2143            mesh.vertices.len(),
2144            mesh.geometry_extents,
2145            draw_batches.as_slice(),
2146            *camera,
2147            Duration::ZERO,
2148            Duration::ZERO,
2149            false,
2150            true,
2151            TessellationStats::default(),
2152            Instant::now(),
2153        )
2154        .map_err(DynamicMeshRenderError::Frame)
2155    }
2156
2157    /// Creates an instanced particle field owned by this renderer.
2158    ///
2159    /// Each instance draws as one screen-space circle quad through a single GPU
2160    /// draw call. The retained CPU snapshot enables later restoration on a
2161    /// recreated renderer.
2162    pub fn create_particle_field(
2163        &self,
2164        instances: &[ParticleInstance2d],
2165    ) -> Result<ParticleField2d, ParticleFieldError> {
2166        self.create_particle_field_with_budget(instances, ParticleRenderBudget::UNBOUNDED)
2167    }
2168
2169    /// Creates an instanced particle field with hard GPU-memory and upload limits.
2170    pub fn create_particle_field_with_budget(
2171        &self,
2172        instances: &[ParticleInstance2d],
2173        budget: ParticleRenderBudget,
2174    ) -> Result<ParticleField2d, ParticleFieldError> {
2175        let instances = particle_instances_to_gpu(instances)?;
2176        let instance_capacity = particle_budgeted_capacity(instances.len(), budget)
2177            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
2178            .ok_or(ParticleFieldError::CapacityTooLarge)?;
2179        let instance_buffer = Arc::new(create_particle_instance_buffer(
2180            &self.device,
2181            instance_capacity,
2182        ));
2183        Ok(ParticleField2d {
2184            renderer_identity: Arc::clone(&self.renderer_identity),
2185            instance_buffer,
2186            statistics: particle_statistics(instances.len(), instances.len(), 0),
2187            instances,
2188            visible_instances: Vec::new(),
2189            instance_capacity,
2190            budget,
2191        })
2192    }
2193
2194    /// Replaces a particle field's hard resource budget, shrinking memory when required.
2195    pub fn set_particle_field_budget(
2196        &self,
2197        field: &mut ParticleField2d,
2198        budget: ParticleRenderBudget,
2199    ) -> Result<(), ParticleFieldError> {
2200        self.validate_particle_field(field)?;
2201        let desired_capacity = particle_budgeted_capacity(field.instances.len(), budget)
2202            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
2203            .ok_or(ParticleFieldError::CapacityTooLarge)?;
2204        if desired_capacity != field.instance_capacity {
2205            field.instance_buffer = Arc::new(create_particle_instance_buffer(
2206                &self.device,
2207                desired_capacity,
2208            ));
2209            field.instance_capacity = desired_capacity;
2210        }
2211        field.budget = budget;
2212        field.visible_instances.clear();
2213        field.statistics = particle_statistics(field.instances.len(), field.instances.len(), 0);
2214        Ok(())
2215    }
2216
2217    /// Replaces all particle instances, reusing GPU capacity whenever possible.
2218    pub fn update_particle_field(
2219        &self,
2220        field: &mut ParticleField2d,
2221        instances: &[ParticleInstance2d],
2222    ) -> Result<ParticleStatistics, ParticleFieldError> {
2223        self.update_particle_field_with_metrics(field, instances)
2224            .map(|report| report.statistics())
2225    }
2226
2227    /// Replaces all particle instances and returns CPU-side preparation metrics.
2228    pub fn update_particle_field_with_metrics(
2229        &self,
2230        field: &mut ParticleField2d,
2231        instances: &[ParticleInstance2d],
2232    ) -> Result<ParticleFieldUpdateReport, ParticleFieldError> {
2233        let update_started_at = Instant::now();
2234        self.validate_particle_field(field)?;
2235        let instances = particle_instances_to_gpu(instances)?;
2236        let desired_capacity = particle_budgeted_capacity(instances.len(), field.budget)
2237            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
2238            .ok_or(ParticleFieldError::CapacityTooLarge)?;
2239        let reallocated = desired_capacity > field.instance_capacity;
2240        if reallocated {
2241            field.instance_capacity = desired_capacity;
2242            field.instance_buffer = Arc::new(create_particle_instance_buffer(
2243                &self.device,
2244                field.instance_capacity,
2245            ));
2246        }
2247        field.statistics = particle_statistics(instances.len(), instances.len(), 0);
2248        field.instances = instances;
2249        Ok(ParticleFieldUpdateReport {
2250            statistics: field.statistics,
2251            preparation: update_started_at.elapsed(),
2252            reallocated,
2253        })
2254    }
2255
2256    /// Replaces a contiguous particle range without reallocating its GPU buffer.
2257    pub fn update_particle_field_range(
2258        &self,
2259        field: &mut ParticleField2d,
2260        first_instance: usize,
2261        instances: &[ParticleInstance2d],
2262    ) -> Result<ParticleStatistics, ParticleFieldError> {
2263        self.update_particle_field_range_with_metrics(field, first_instance, instances)
2264            .map(|report| report.statistics())
2265    }
2266
2267    /// Replaces a particle range and returns CPU-side preparation metrics.
2268    pub fn update_particle_field_range_with_metrics(
2269        &self,
2270        field: &mut ParticleField2d,
2271        first_instance: usize,
2272        instances: &[ParticleInstance2d],
2273    ) -> Result<ParticleFieldUpdateReport, ParticleFieldError> {
2274        let update_started_at = Instant::now();
2275        self.validate_particle_field(field)?;
2276        let range = particle_update_range(first_instance, instances.len(), field.instances.len())?;
2277        let instances = particle_instances_to_gpu(instances)?;
2278        if !instances.is_empty() {
2279            field.instances[range].copy_from_slice(&instances);
2280        }
2281        field.statistics = particle_statistics(field.instances.len(), field.instances.len(), 0);
2282        Ok(ParticleFieldUpdateReport {
2283            statistics: field.statistics,
2284            preparation: update_started_at.elapsed(),
2285            reallocated: false,
2286        })
2287    }
2288
2289    /// Recreates a particle field on this renderer from retained CPU instances.
2290    pub fn restore_particle_field(
2291        &self,
2292        source: &ParticleField2d,
2293    ) -> Result<ParticleField2d, ParticleFieldError> {
2294        restore_particle_field_resources(
2295            &self.device,
2296            &self.queue,
2297            Arc::clone(&self.renderer_identity),
2298            source,
2299        )
2300    }
2301
2302    /// Creates a single-channel floating-point texture from a validated scalar grid.
2303    pub fn create_scalar_field_texture(
2304        &self,
2305        field: ScalarField,
2306    ) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
2307        create_scalar_field_texture_resources(
2308            &self.device,
2309            &self.queue,
2310            Arc::clone(&self.renderer_identity),
2311            field,
2312        )
2313    }
2314
2315    /// Creates an offscreen target with physical texture dimensions.
2316    pub fn create_render_target(
2317        &self,
2318        width: u32,
2319        height: u32,
2320    ) -> Result<RenderTarget2d, RenderTargetError> {
2321        if width == 0 || height == 0 {
2322            return Err(RenderTargetError::ZeroDimension);
2323        }
2324        if width > self.device.limits().max_texture_dimension_2d
2325            || height > self.device.limits().max_texture_dimension_2d
2326        {
2327            return Err(RenderTargetError::DimensionsTooLarge);
2328        }
2329        let allocation_bytes = render_target_allocation_bytes(self.config.format, width, height)
2330            .ok_or(RenderTargetError::DimensionsTooLarge)?;
2331        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
2332            label: Some("sim-engine render target"),
2333            size: wgpu::Extent3d {
2334                width,
2335                height,
2336                depth_or_array_layers: 1,
2337            },
2338            mip_level_count: 1,
2339            sample_count: 1,
2340            dimension: wgpu::TextureDimension::D2,
2341            format: self.config.format,
2342            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
2343                | wgpu::TextureUsages::TEXTURE_BINDING
2344                | wgpu::TextureUsages::COPY_SRC,
2345            view_formats: &[],
2346        });
2347        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
2348        Ok(RenderTarget2d {
2349            renderer_identity: Arc::clone(&self.renderer_identity),
2350            resource_identity: Arc::new(()),
2351            _texture: texture,
2352            view,
2353            width,
2354            height,
2355            allocation_bytes,
2356        })
2357    }
2358
2359    /// Creates an empty ping-pong target pair for temporal accumulation.
2360    pub fn create_trail_buffer(
2361        &mut self,
2362        width: u32,
2363        height: u32,
2364    ) -> Result<TrailBuffer2d, RenderTargetError> {
2365        let front = self.create_render_target(width, height)?;
2366        let back = self.create_render_target(width, height)?;
2367        let trails = TrailBuffer2d {
2368            renderer_identity: Arc::clone(&self.renderer_identity),
2369            front,
2370            back,
2371        };
2372        self.draw_clear_trail_buffer(&trails, Color::rgba(0.0, 0.0, 0.0, 0.0), Instant::now());
2373        Ok(trails)
2374    }
2375
2376    /// Recreates an empty target with the source dimensions after device recovery.
2377    ///
2378    /// GPU pixels are deliberately not retained; callers redraw their source
2379    /// state into the restored target.
2380    pub fn restore_render_target(
2381        &self,
2382        source: &RenderTarget2d,
2383    ) -> Result<RenderTarget2d, RenderTargetError> {
2384        self.create_render_target(source.width(), source.height())
2385    }
2386
2387    /// Recreates an empty, deterministically cleared trail buffer after recovery.
2388    pub fn restore_trail_buffer(
2389        &mut self,
2390        source: &TrailBuffer2d,
2391    ) -> Result<TrailBuffer2d, RenderTargetError> {
2392        self.create_trail_buffer(source.width(), source.height())
2393    }
2394
2395    /// Retains one bounded frame of history and composites a fresh source target.
2396    ///
2397    /// `retention` and `source_opacity` must be finite values in `0.0..=1.0`.
2398    /// The source must be a distinct target; use [`WgpuRenderer::clear_trail_buffer`]
2399    /// to discard accumulated history deterministically.
2400    pub fn accumulate_trail_buffer(
2401        &mut self,
2402        trails: &mut TrailBuffer2d,
2403        source: &RenderTarget2d,
2404        retention: f32,
2405        source_opacity: f32,
2406        source_blend: BlendMode,
2407    ) -> Result<RenderReport, RenderTargetError> {
2408        self.validate_trail_buffer(trails)?;
2409        self.validate_render_target(source)?;
2410        if Arc::ptr_eq(&source.resource_identity, &trails.front.resource_identity)
2411            || Arc::ptr_eq(&source.resource_identity, &trails.back.resource_identity)
2412        {
2413            return Err(RenderTargetError::SourceAliasesDestination);
2414        }
2415        if !retention.is_finite()
2416            || !(0.0..=1.0).contains(&retention)
2417            || !source_opacity.is_finite()
2418            || !(0.0..=1.0).contains(&source_opacity)
2419        {
2420            return Err(RenderTargetError::InvalidOpacity);
2421        }
2422        Ok(self.draw_trail_accumulation(
2423            trails,
2424            source,
2425            retention,
2426            source_opacity,
2427            source_blend,
2428            Instant::now(),
2429        ))
2430    }
2431
2432    /// Clears both ping-pong targets, resetting all retained temporal history.
2433    pub fn clear_trail_buffer(
2434        &mut self,
2435        trails: &mut TrailBuffer2d,
2436        color: Color,
2437    ) -> Result<RenderReport, RenderTargetError> {
2438        self.validate_trail_buffer(trails)?;
2439        if !color.is_normalized() {
2440            return Err(RenderTargetError::InvalidBackground);
2441        }
2442        Ok(self.draw_clear_trail_buffer(trails, color, Instant::now()))
2443    }
2444
2445    /// Presents the most recently accumulated temporal target.
2446    pub fn compose_trail_buffer(
2447        &mut self,
2448        trails: &TrailBuffer2d,
2449        blend_mode: BlendMode,
2450        opacity: f32,
2451        background: Color,
2452    ) -> Result<RenderReport, RenderTargetError> {
2453        self.validate_trail_buffer(trails)?;
2454        self.compose_render_target(&trails.front, blend_mode, opacity, background)
2455    }
2456
2457    /// Replaces scalar data, recreating the texture only when dimensions change.
2458    pub fn update_scalar_field_texture(
2459        &self,
2460        texture: &mut ScalarFieldTexture,
2461        field: ScalarField,
2462    ) -> Result<ScalarFieldUploadReport, ScalarFieldTextureError> {
2463        let upload_started_at = Instant::now();
2464        self.validate_scalar_field_texture(texture)?;
2465        let reallocated = texture.width() != field.width() || texture.height() != field.height();
2466        if reallocated {
2467            texture.texture = create_scalar_field_texture(&self.device, &field)?;
2468        }
2469        upload_scalar_field_texture(&self.queue, &texture.texture, &field)?;
2470        texture.field = field;
2471        Ok(ScalarFieldUploadReport {
2472            upload: upload_started_at.elapsed(),
2473            reallocated,
2474        })
2475    }
2476
2477    /// Updates a rectangular scalar texture region without recreating it.
2478    pub fn update_scalar_field_texture_region(
2479        &self,
2480        texture: &mut ScalarFieldTexture,
2481        x: usize,
2482        y: usize,
2483        width: usize,
2484        height: usize,
2485        values: &[f32],
2486    ) -> Result<ScalarFieldUploadReport, ScalarFieldTextureError> {
2487        let upload_started_at = Instant::now();
2488        self.validate_scalar_field_texture(texture)?;
2489        texture
2490            .field
2491            .replace_region(x, y, width, height, values)
2492            .map_err(|error| match error {
2493                crate::ScalarFieldError::InvalidValueCount { .. } => {
2494                    ScalarFieldTextureError::InvalidUpdateValueCount
2495                }
2496                crate::ScalarFieldError::NonFiniteValue => {
2497                    ScalarFieldTextureError::NonFiniteUpdateValue
2498                }
2499                _ => ScalarFieldTextureError::UpdateRegionOutOfBounds,
2500            })?;
2501        upload_scalar_field_texture_region(
2502            &self.queue,
2503            &texture.texture,
2504            x,
2505            y,
2506            width,
2507            height,
2508            values,
2509        )?;
2510        Ok(ScalarFieldUploadReport {
2511            upload: upload_started_at.elapsed(),
2512            reallocated: false,
2513        })
2514    }
2515
2516    /// Recreates a scalar texture on this renderer from its retained CPU grid.
2517    pub fn restore_scalar_field_texture(
2518        &self,
2519        source: &ScalarFieldTexture,
2520    ) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
2521        self.create_scalar_field_texture(source.field.clone())
2522    }
2523
2524    /// Draws a scalar texture across the logical viewport through a color map.
2525    ///
2526    /// `value_range` maps `minimum` to the first color-map entry and `maximum`
2527    /// to the last. Values outside the range clamp to those endpoints.
2528    pub fn render_scalar_field_texture(
2529        &mut self,
2530        texture: &ScalarFieldTexture,
2531        color_map: &ColorMap,
2532        value_range: (f32, f32),
2533        background: Color,
2534    ) -> Result<RenderStatus, ScalarFieldRenderError> {
2535        self.render_scalar_field_texture_with_metrics(texture, color_map, value_range, background)
2536            .map(RenderReport::status)
2537    }
2538
2539    /// Draws a scalar texture and returns normal CPU-side renderer metrics.
2540    pub fn render_scalar_field_texture_with_metrics(
2541        &mut self,
2542        texture: &ScalarFieldTexture,
2543        color_map: &ColorMap,
2544        (minimum, maximum): (f32, f32),
2545        background: Color,
2546    ) -> Result<RenderReport, ScalarFieldRenderError> {
2547        self.validate_scalar_field_texture(texture)
2548            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
2549        let value_extent = scalar_value_range_extent(minimum, maximum)
2550            .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
2551        if !background.is_normalized() {
2552            return Err(ScalarFieldRenderError::InvalidBackground);
2553        }
2554        self.draw_scalar_field_texture(
2555            texture,
2556            color_map,
2557            minimum,
2558            value_extent,
2559            ScalarFieldSampling::Nearest,
2560            background,
2561            Instant::now(),
2562        )
2563        .map_err(ScalarFieldRenderError::Frame)
2564    }
2565
2566    /// Draws a scalar texture with an explicit texel sampling mode.
2567    pub fn render_scalar_field_texture_with_sampling(
2568        &mut self,
2569        texture: &ScalarFieldTexture,
2570        color_map: &ColorMap,
2571        (minimum, maximum): (f32, f32),
2572        sampling: ScalarFieldSampling,
2573        background: Color,
2574    ) -> Result<RenderStatus, ScalarFieldRenderError> {
2575        self.validate_scalar_field_texture(texture)
2576            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
2577        let value_extent = scalar_value_range_extent(minimum, maximum)
2578            .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
2579        if !background.is_normalized() {
2580            return Err(ScalarFieldRenderError::InvalidBackground);
2581        }
2582        self.draw_scalar_field_texture(
2583            texture,
2584            color_map,
2585            minimum,
2586            value_extent,
2587            sampling,
2588            background,
2589            Instant::now(),
2590        )
2591        .map(RenderReport::status)
2592        .map_err(ScalarFieldRenderError::Frame)
2593    }
2594
2595    /// Renders a scalar heatmap into an offscreen target instead of presenting it.
2596    pub fn render_scalar_field_texture_to_target(
2597        &mut self,
2598        target: &RenderTarget2d,
2599        texture: &ScalarFieldTexture,
2600        color_map: &ColorMap,
2601        value_range: (f32, f32),
2602        background: Color,
2603    ) -> Result<RenderReport, ScalarFieldRenderError> {
2604        self.render_scalar_field_texture_to_target_with_sampling(
2605            target,
2606            texture,
2607            color_map,
2608            value_range,
2609            ScalarFieldSampling::Nearest,
2610            background,
2611        )
2612    }
2613
2614    /// Renders a scalar heatmap into a target with explicit source sampling.
2615    pub fn render_scalar_field_texture_to_target_with_sampling(
2616        &mut self,
2617        target: &RenderTarget2d,
2618        texture: &ScalarFieldTexture,
2619        color_map: &ColorMap,
2620        (minimum, maximum): (f32, f32),
2621        sampling: ScalarFieldSampling,
2622        background: Color,
2623    ) -> Result<RenderReport, ScalarFieldRenderError> {
2624        self.validate_render_target(target)
2625            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
2626        self.validate_scalar_field_texture(texture)
2627            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
2628        let value_extent = scalar_value_range_extent(minimum, maximum)
2629            .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
2630        if !background.is_normalized() {
2631            return Err(ScalarFieldRenderError::InvalidBackground);
2632        }
2633        Ok(self.draw_scalar_field_texture_to_target(
2634            target,
2635            texture,
2636            color_map,
2637            minimum,
2638            value_extent,
2639            sampling,
2640            background,
2641            Instant::now(),
2642        ))
2643    }
2644
2645    /// Composes a previously rendered target over the presentation surface.
2646    pub fn compose_render_target(
2647        &mut self,
2648        target: &RenderTarget2d,
2649        blend_mode: BlendMode,
2650        opacity: f32,
2651        background: Color,
2652    ) -> Result<RenderReport, RenderTargetError> {
2653        self.validate_render_target(target)?;
2654        if !opacity.is_finite() || !(0.0..=1.0).contains(&opacity) {
2655            return Err(RenderTargetError::InvalidOpacity);
2656        }
2657        if !background.is_normalized() {
2658            return Err(RenderTargetError::InvalidBackground);
2659        }
2660        self.draw_composed_render_target(target, blend_mode, opacity, background, Instant::now())
2661            .map_err(RenderTargetError::Frame)
2662    }
2663
2664    /// Draws a particle field with a normalized clear color.
2665    pub fn render_particle_field(
2666        &mut self,
2667        field: &mut ParticleField2d,
2668        background: Color,
2669        camera: &Camera2d,
2670    ) -> Result<RenderStatus, ParticleFieldRenderError> {
2671        self.render_particle_field_with_metrics(field, background, camera)
2672            .map(RenderReport::status)
2673    }
2674
2675    /// Draws a particle field and returns regular per-frame renderer metrics.
2676    pub fn render_particle_field_with_metrics(
2677        &mut self,
2678        field: &mut ParticleField2d,
2679        background: Color,
2680        camera: &Camera2d,
2681    ) -> Result<RenderReport, ParticleFieldRenderError> {
2682        self.validate_particle_field(field)
2683            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
2684        if !background.is_normalized() {
2685            return Err(ParticleFieldRenderError::InvalidBackground);
2686        }
2687        self.draw_particle_field(background, field, *camera, Instant::now())
2688            .map_err(|error| match error {
2689                RendererFrameError::InvalidGeometryTransform => {
2690                    ParticleFieldRenderError::InvalidGeometryTransform
2691                }
2692                other => ParticleFieldRenderError::Frame(other),
2693            })
2694    }
2695
2696    /// Draws a particle field into an offscreen target.
2697    ///
2698    /// Target dimensions may be lower than the presentation surface to bound
2699    /// raster cost. Camera coordinates and particle radii remain expressed in
2700    /// logical presentation pixels, so composing the target back to the surface
2701    /// preserves layout while trading only raster resolution.
2702    pub fn render_particle_field_to_target(
2703        &mut self,
2704        target: &RenderTarget2d,
2705        field: &mut ParticleField2d,
2706        camera: &Camera2d,
2707        load: RenderTargetLoad,
2708    ) -> Result<RenderReport, ParticleFieldRenderError> {
2709        self.validate_render_target(target)
2710            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
2711        self.validate_particle_field(field)
2712            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
2713        if matches!(load, RenderTargetLoad::Clear(color) if !color.is_normalized()) {
2714            return Err(ParticleFieldRenderError::InvalidBackground);
2715        }
2716        self.draw_particle_field_to_target(target, field, *camera, load, Instant::now())
2717            .map_err(|error| match error {
2718                RendererFrameError::InvalidGeometryTransform => {
2719                    ParticleFieldRenderError::InvalidGeometryTransform
2720                }
2721                other => ParticleFieldRenderError::Frame(other),
2722            })
2723    }
2724
2725    /// Draws geometry previously uploaded by [`WgpuRenderer::prepare_scene`].
2726    ///
2727    /// Camera and viewport changes are applied by the vertex shader and do not
2728    /// rebuild or re-upload the prepared geometry.
2729    pub fn render_prepared(
2730        &mut self,
2731        scene: &PreparedScene,
2732        camera: &Camera2d,
2733    ) -> Result<RenderStatus, PreparedSceneRenderError> {
2734        self.render_prepared_with_metrics(scene, camera)
2735            .map(RenderReport::status)
2736    }
2737
2738    /// Draws prepared geometry and reports per-frame CPU timing.
2739    ///
2740    /// Tessellation and geometry upload durations are zero because both happened
2741    /// in [`WgpuRenderer::prepare_scene`]. The camera uniform is still updated
2742    /// once per frame.
2743    pub fn render_prepared_with_metrics(
2744        &mut self,
2745        scene: &PreparedScene,
2746        camera: &Camera2d,
2747    ) -> Result<RenderReport, PreparedSceneRenderError> {
2748        if !prepared_scene_belongs_to(&self.renderer_identity, &scene.renderer_identity) {
2749            return Err(PreparedSceneRenderError::RendererMismatch);
2750        }
2751
2752        self.draw_geometry(
2753            scene.background,
2754            &scene.vertex_buffer,
2755            scene.vertex_count,
2756            scene.geometry_extents,
2757            &scene.draw_batches,
2758            *camera,
2759            Duration::ZERO,
2760            Duration::ZERO,
2761            true,
2762            false,
2763            scene.tessellation,
2764            Instant::now(),
2765        )
2766        .map_err(PreparedSceneRenderError::Frame)
2767    }
2768
2769    #[allow(clippy::too_many_arguments)]
2770    fn draw_geometry(
2771        &mut self,
2772        background: Color,
2773        vertex_buffer: &wgpu::Buffer,
2774        vertex_count: usize,
2775        geometry_extents: GeometryExtents,
2776        draw_batches: &[PreparedDrawBatch],
2777        camera: Camera2d,
2778        tessellation: Duration,
2779        upload: Duration,
2780        geometry_reused: bool,
2781        geometry_streamed: bool,
2782        tessellation_stats: TessellationStats,
2783        frame_started_at: Instant,
2784    ) -> Result<RenderReport, RendererFrameError> {
2785        let (logical_width, logical_height) = self.logical_size();
2786        let viewport = LogicalViewport::new(logical_width, logical_height)
2787            .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
2788        let camera_uniform_upload_started_at = Instant::now();
2789        let Some(camera_uniform) = CameraUniform::new(camera, viewport) else {
2790            return Err(RendererFrameError::InvalidGeometryTransform);
2791        };
2792        if !geometry_extents.is_safe_for(camera_uniform) {
2793            return Err(RendererFrameError::InvalidGeometryTransform);
2794        }
2795        self.queue.write_buffer(
2796            &self.camera_uniform_buffer,
2797            0,
2798            bytemuck::bytes_of(&camera_uniform),
2799        );
2800        let camera_uniform_upload = camera_uniform_upload_started_at.elapsed();
2801
2802        let surface_acquire_started_at = Instant::now();
2803        let surface_texture = match self.surface.get_current_texture() {
2804            wgpu::CurrentSurfaceTexture::Success(texture)
2805            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
2806            wgpu::CurrentSurfaceTexture::Timeout => {
2807                return Ok(render_report(
2808                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
2809                    tessellation,
2810                    upload,
2811                    camera_uniform_upload,
2812                    surface_acquire_started_at.elapsed(),
2813                    Duration::ZERO,
2814                    frame_started_at.elapsed(),
2815                    geometry_reused,
2816                    geometry_streamed,
2817                    tessellation_stats,
2818                ));
2819            }
2820            wgpu::CurrentSurfaceTexture::Occluded => {
2821                return Ok(render_report(
2822                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
2823                    tessellation,
2824                    upload,
2825                    camera_uniform_upload,
2826                    surface_acquire_started_at.elapsed(),
2827                    Duration::ZERO,
2828                    frame_started_at.elapsed(),
2829                    geometry_reused,
2830                    geometry_streamed,
2831                    tessellation_stats,
2832                ));
2833            }
2834            wgpu::CurrentSurfaceTexture::Outdated => {
2835                self.resize(self.config.width, self.config.height);
2836                return Ok(render_report(
2837                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
2838                    tessellation,
2839                    upload,
2840                    camera_uniform_upload,
2841                    surface_acquire_started_at.elapsed(),
2842                    Duration::ZERO,
2843                    frame_started_at.elapsed(),
2844                    geometry_reused,
2845                    geometry_streamed,
2846                    tessellation_stats,
2847                ));
2848            }
2849            wgpu::CurrentSurfaceTexture::Lost => {
2850                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
2851            }
2852            wgpu::CurrentSurfaceTexture::Validation => {
2853                return Err(RendererFrameError::Surface(
2854                    RendererSurfaceStatus::Validation,
2855                ));
2856            }
2857        };
2858        let surface_acquire = surface_acquire_started_at.elapsed();
2859
2860        let encode_submit_present_started_at = Instant::now();
2861        let surface_view = surface_texture
2862            .texture
2863            .create_view(&wgpu::TextureViewDescriptor::default());
2864        let (view, resolve_target) = match &self.multisample_target {
2865            Some(target) => (&target.view, Some(&surface_view)),
2866            None => (&surface_view, None),
2867        };
2868
2869        let mut encoder = self
2870            .device
2871            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
2872                label: Some("sim-engine render encoder"),
2873            });
2874
2875        {
2876            let color_attachment = wgpu::RenderPassColorAttachment {
2877                view,
2878                depth_slice: None,
2879                resolve_target,
2880                ops: wgpu::Operations {
2881                    load: wgpu::LoadOp::Clear(background.to_wgpu()),
2882                    store: wgpu::StoreOp::Store,
2883                },
2884            };
2885            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
2886                label: Some("sim-engine render pass"),
2887                color_attachments: &[Some(color_attachment)],
2888                depth_stencil_attachment: None,
2889                timestamp_writes: None,
2890                occlusion_query_set: None,
2891                multiview_mask: None,
2892            });
2893
2894            if vertex_count > 0 {
2895                let pipeline = if geometry_streamed {
2896                    &self.dynamic_pipeline
2897                } else {
2898                    &self.pipeline
2899                };
2900                pass.set_pipeline(pipeline);
2901                pass.set_bind_group(0, &self.camera_bind_group, &[]);
2902                pass.set_vertex_buffer(0, vertex_buffer.slice(..));
2903                for batch in draw_batches {
2904                    let scissor = match batch.screen_clip {
2905                        Some(screen_clip) => {
2906                            let Some(scissor) = screen_clip_to_scissor(
2907                                screen_clip,
2908                                viewport,
2909                                self.scale_factor as f32,
2910                            ) else {
2911                                continue;
2912                            };
2913                            scissor
2914                        }
2915                        None => ScissorRect {
2916                            x: 0,
2917                            y: 0,
2918                            width: self.config.width,
2919                            height: self.config.height,
2920                        },
2921                    };
2922                    pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
2923                    pass.draw(batch.vertex_range.clone(), 0..1);
2924                }
2925            }
2926        }
2927
2928        self.queue.submit([encoder.finish()]);
2929        self.queue.present(surface_texture);
2930        let encode_submit_present = encode_submit_present_started_at.elapsed();
2931
2932        Ok(render_report(
2933            RenderStatus::Drawn,
2934            tessellation,
2935            upload,
2936            camera_uniform_upload,
2937            surface_acquire,
2938            encode_submit_present,
2939            frame_started_at.elapsed(),
2940            geometry_reused,
2941            geometry_streamed,
2942            tessellation_stats,
2943        ))
2944    }
2945
2946    #[allow(clippy::too_many_arguments)]
2947    fn draw_scalar_field_texture(
2948        &mut self,
2949        texture: &ScalarFieldTexture,
2950        color_map: &ColorMap,
2951        minimum: f32,
2952        value_extent: f32,
2953        sampling: ScalarFieldSampling,
2954        background: Color,
2955        frame_started_at: Instant,
2956    ) -> Result<RenderReport, RendererFrameError> {
2957        let upload_started_at = Instant::now();
2958        let color_map_view = self.color_map_view(color_map);
2959        let scalar_view = texture
2960            .texture
2961            .create_view(&wgpu::TextureViewDescriptor::default());
2962        let uniform = HeatmapUniform {
2963            value_range: [minimum, value_extent, 0.0, 0.0],
2964            dimensions: [
2965                texture.width() as u32,
2966                texture.height() as u32,
2967                sampling.shader_value(),
2968                0,
2969            ],
2970        };
2971        self.queue.write_buffer(
2972            &self.heatmap_uniform_buffer,
2973            0,
2974            bytemuck::bytes_of(&uniform),
2975        );
2976        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2977            label: Some("sim-engine heatmap bind group"),
2978            layout: &self.heatmap_bind_group_layout,
2979            entries: &[
2980                wgpu::BindGroupEntry {
2981                    binding: 0,
2982                    resource: wgpu::BindingResource::TextureView(&scalar_view),
2983                },
2984                wgpu::BindGroupEntry {
2985                    binding: 1,
2986                    resource: wgpu::BindingResource::TextureView(&color_map_view),
2987                },
2988                wgpu::BindGroupEntry {
2989                    binding: 2,
2990                    resource: self.heatmap_uniform_buffer.as_entire_binding(),
2991                },
2992            ],
2993        });
2994        let upload = upload_started_at.elapsed();
2995        let acquire_started_at = Instant::now();
2996        let surface_texture = match self.surface.get_current_texture() {
2997            wgpu::CurrentSurfaceTexture::Success(texture)
2998            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
2999            wgpu::CurrentSurfaceTexture::Timeout => {
3000                return Ok(render_report(
3001                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
3002                    Duration::ZERO,
3003                    upload,
3004                    Duration::ZERO,
3005                    acquire_started_at.elapsed(),
3006                    Duration::ZERO,
3007                    frame_started_at.elapsed(),
3008                    false,
3009                    true,
3010                    TessellationStats::default(),
3011                ));
3012            }
3013            wgpu::CurrentSurfaceTexture::Occluded => {
3014                return Ok(render_report(
3015                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
3016                    Duration::ZERO,
3017                    upload,
3018                    Duration::ZERO,
3019                    acquire_started_at.elapsed(),
3020                    Duration::ZERO,
3021                    frame_started_at.elapsed(),
3022                    false,
3023                    true,
3024                    TessellationStats::default(),
3025                ));
3026            }
3027            wgpu::CurrentSurfaceTexture::Outdated => {
3028                self.resize(self.config.width, self.config.height);
3029                return Ok(render_report(
3030                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
3031                    Duration::ZERO,
3032                    upload,
3033                    Duration::ZERO,
3034                    acquire_started_at.elapsed(),
3035                    Duration::ZERO,
3036                    frame_started_at.elapsed(),
3037                    false,
3038                    true,
3039                    TessellationStats::default(),
3040                ));
3041            }
3042            wgpu::CurrentSurfaceTexture::Lost => {
3043                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
3044            }
3045            wgpu::CurrentSurfaceTexture::Validation => {
3046                return Err(RendererFrameError::Surface(
3047                    RendererSurfaceStatus::Validation,
3048                ));
3049            }
3050        };
3051        let surface_acquire = acquire_started_at.elapsed();
3052        let encode_started_at = Instant::now();
3053        let surface_view = surface_texture
3054            .texture
3055            .create_view(&wgpu::TextureViewDescriptor::default());
3056        let (view, resolve_target) = match &self.multisample_target {
3057            Some(target) => (&target.view, Some(&surface_view)),
3058            None => (&surface_view, None),
3059        };
3060        let mut encoder = self
3061            .device
3062            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3063                label: Some("sim-engine heatmap encoder"),
3064            });
3065        {
3066            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
3067                label: Some("sim-engine heatmap pass"),
3068                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
3069                    view,
3070                    depth_slice: None,
3071                    resolve_target,
3072                    ops: wgpu::Operations {
3073                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
3074                        store: wgpu::StoreOp::Store,
3075                    },
3076                })],
3077                depth_stencil_attachment: None,
3078                timestamp_writes: None,
3079                occlusion_query_set: None,
3080                multiview_mask: None,
3081            });
3082            pass.set_pipeline(&self.heatmap_pipeline);
3083            pass.set_bind_group(0, &bind_group, &[]);
3084            pass.draw(0..6, 0..1);
3085        }
3086        self.queue.submit([encoder.finish()]);
3087        self.queue.present(surface_texture);
3088        Ok(render_report(
3089            RenderStatus::Drawn,
3090            Duration::ZERO,
3091            upload,
3092            Duration::ZERO,
3093            surface_acquire,
3094            encode_started_at.elapsed(),
3095            frame_started_at.elapsed(),
3096            false,
3097            true,
3098            TessellationStats::default(),
3099        ))
3100    }
3101
3102    #[allow(clippy::too_many_arguments)]
3103    fn draw_scalar_field_texture_to_target(
3104        &mut self,
3105        target: &RenderTarget2d,
3106        texture: &ScalarFieldTexture,
3107        color_map: &ColorMap,
3108        minimum: f32,
3109        value_extent: f32,
3110        sampling: ScalarFieldSampling,
3111        background: Color,
3112        frame_started_at: Instant,
3113    ) -> RenderReport {
3114        let upload_started_at = Instant::now();
3115        let color_map_view = self.color_map_view(color_map);
3116        let scalar_view = texture
3117            .texture
3118            .create_view(&wgpu::TextureViewDescriptor::default());
3119        self.queue.write_buffer(
3120            &self.heatmap_uniform_buffer,
3121            0,
3122            bytemuck::bytes_of(&HeatmapUniform {
3123                value_range: [minimum, value_extent, 0.0, 0.0],
3124                dimensions: [
3125                    texture.width() as u32,
3126                    texture.height() as u32,
3127                    sampling.shader_value(),
3128                    0,
3129                ],
3130            }),
3131        );
3132        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3133            label: Some("sim-engine target heatmap bind group"),
3134            layout: &self.heatmap_bind_group_layout,
3135            entries: &[
3136                wgpu::BindGroupEntry {
3137                    binding: 0,
3138                    resource: wgpu::BindingResource::TextureView(&scalar_view),
3139                },
3140                wgpu::BindGroupEntry {
3141                    binding: 1,
3142                    resource: wgpu::BindingResource::TextureView(&color_map_view),
3143                },
3144                wgpu::BindGroupEntry {
3145                    binding: 2,
3146                    resource: self.heatmap_uniform_buffer.as_entire_binding(),
3147                },
3148            ],
3149        });
3150        let upload = upload_started_at.elapsed();
3151        let encode_started_at = Instant::now();
3152        let mut encoder = self
3153            .device
3154            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3155                label: Some("sim-engine render-target heatmap encoder"),
3156            });
3157        {
3158            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
3159                label: Some("sim-engine render-target heatmap pass"),
3160                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
3161                    view: &target.view,
3162                    depth_slice: None,
3163                    resolve_target: None,
3164                    ops: wgpu::Operations {
3165                        load: wgpu::LoadOp::Clear(premultiplied_wgpu_color(background)),
3166                        store: wgpu::StoreOp::Store,
3167                    },
3168                })],
3169                depth_stencil_attachment: None,
3170                timestamp_writes: None,
3171                occlusion_query_set: None,
3172                multiview_mask: None,
3173            });
3174            pass.set_pipeline(&self.target_heatmap_pipeline);
3175            pass.set_bind_group(0, &bind_group, &[]);
3176            pass.draw(0..6, 0..1);
3177        }
3178        self.queue.submit([encoder.finish()]);
3179        render_report(
3180            RenderStatus::Drawn,
3181            Duration::ZERO,
3182            upload,
3183            Duration::ZERO,
3184            Duration::ZERO,
3185            encode_started_at.elapsed(),
3186            frame_started_at.elapsed(),
3187            false,
3188            true,
3189            TessellationStats::default(),
3190        )
3191    }
3192
3193    fn draw_composed_render_target(
3194        &mut self,
3195        target: &RenderTarget2d,
3196        blend_mode: BlendMode,
3197        opacity: f32,
3198        background: Color,
3199        frame_started_at: Instant,
3200    ) -> Result<RenderReport, RendererFrameError> {
3201        let upload_started_at = Instant::now();
3202        self.queue.write_buffer(
3203            &self.composition_pipelines.uniform_buffer,
3204            0,
3205            bytemuck::bytes_of(&CompositeUniform {
3206                opacity: [opacity, 0.0, 0.0, 0.0],
3207            }),
3208        );
3209        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3210            label: Some("sim-engine composition bind group"),
3211            layout: &self.composition_pipelines.bind_group_layout,
3212            entries: &[
3213                wgpu::BindGroupEntry {
3214                    binding: 0,
3215                    resource: wgpu::BindingResource::TextureView(&target.view),
3216                },
3217                wgpu::BindGroupEntry {
3218                    binding: 1,
3219                    resource: self
3220                        .composition_pipelines
3221                        .uniform_buffer
3222                        .as_entire_binding(),
3223                },
3224            ],
3225        });
3226        let upload = upload_started_at.elapsed();
3227        let acquire_started_at = Instant::now();
3228        let surface_texture = match self.surface.get_current_texture() {
3229            wgpu::CurrentSurfaceTexture::Success(texture)
3230            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
3231            wgpu::CurrentSurfaceTexture::Timeout => {
3232                return Ok(render_report(
3233                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
3234                    Duration::ZERO,
3235                    upload,
3236                    Duration::ZERO,
3237                    acquire_started_at.elapsed(),
3238                    Duration::ZERO,
3239                    frame_started_at.elapsed(),
3240                    false,
3241                    true,
3242                    TessellationStats::default(),
3243                ));
3244            }
3245            wgpu::CurrentSurfaceTexture::Occluded => {
3246                return Ok(render_report(
3247                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
3248                    Duration::ZERO,
3249                    upload,
3250                    Duration::ZERO,
3251                    acquire_started_at.elapsed(),
3252                    Duration::ZERO,
3253                    frame_started_at.elapsed(),
3254                    false,
3255                    true,
3256                    TessellationStats::default(),
3257                ));
3258            }
3259            wgpu::CurrentSurfaceTexture::Outdated => {
3260                self.resize(self.config.width, self.config.height);
3261                return Ok(render_report(
3262                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
3263                    Duration::ZERO,
3264                    upload,
3265                    Duration::ZERO,
3266                    acquire_started_at.elapsed(),
3267                    Duration::ZERO,
3268                    frame_started_at.elapsed(),
3269                    false,
3270                    true,
3271                    TessellationStats::default(),
3272                ));
3273            }
3274            wgpu::CurrentSurfaceTexture::Lost => {
3275                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
3276            }
3277            wgpu::CurrentSurfaceTexture::Validation => {
3278                return Err(RendererFrameError::Surface(
3279                    RendererSurfaceStatus::Validation,
3280                ));
3281            }
3282        };
3283        let surface_acquire = acquire_started_at.elapsed();
3284        let encode_started_at = Instant::now();
3285        let surface_view = surface_texture
3286            .texture
3287            .create_view(&wgpu::TextureViewDescriptor::default());
3288        let (view, resolve_target) = match &self.multisample_target {
3289            Some(multisample_target) => (&multisample_target.view, Some(&surface_view)),
3290            None => (&surface_view, None),
3291        };
3292        let mut encoder = self
3293            .device
3294            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3295                label: Some("sim-engine composition encoder"),
3296            });
3297        {
3298            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
3299                label: Some("sim-engine composition pass"),
3300                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
3301                    view,
3302                    depth_slice: None,
3303                    resolve_target,
3304                    ops: wgpu::Operations {
3305                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
3306                        store: wgpu::StoreOp::Store,
3307                    },
3308                })],
3309                depth_stencil_attachment: None,
3310                timestamp_writes: None,
3311                occlusion_query_set: None,
3312                multiview_mask: None,
3313            });
3314            pass.set_pipeline(self.composition_pipelines.pipeline(blend_mode));
3315            pass.set_bind_group(0, &bind_group, &[]);
3316            pass.draw(0..6, 0..1);
3317        }
3318        self.queue.submit([encoder.finish()]);
3319        self.queue.present(surface_texture);
3320        Ok(render_report(
3321            RenderStatus::Drawn,
3322            Duration::ZERO,
3323            upload,
3324            Duration::ZERO,
3325            surface_acquire,
3326            encode_started_at.elapsed(),
3327            frame_started_at.elapsed(),
3328            false,
3329            true,
3330            TessellationStats::default(),
3331        ))
3332    }
3333
3334    #[allow(clippy::too_many_arguments)]
3335    fn draw_trail_accumulation(
3336        &mut self,
3337        trails: &mut TrailBuffer2d,
3338        source: &RenderTarget2d,
3339        retention: f32,
3340        source_opacity: f32,
3341        source_blend: BlendMode,
3342        frame_started_at: Instant,
3343    ) -> RenderReport {
3344        let upload_started_at = Instant::now();
3345        self.queue.write_buffer(
3346            &self.target_composition_pipelines.secondary_uniform_buffer,
3347            0,
3348            bytemuck::bytes_of(&CompositeUniform {
3349                opacity: [retention, 0.0, 0.0, 0.0],
3350            }),
3351        );
3352        self.queue.write_buffer(
3353            &self.target_composition_pipelines.uniform_buffer,
3354            0,
3355            bytemuck::bytes_of(&CompositeUniform {
3356                opacity: [source_opacity, 0.0, 0.0, 0.0],
3357            }),
3358        );
3359        let history_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3360            label: Some("sim-engine trail history bind group"),
3361            layout: &self.target_composition_pipelines.bind_group_layout,
3362            entries: &[
3363                wgpu::BindGroupEntry {
3364                    binding: 0,
3365                    resource: wgpu::BindingResource::TextureView(&trails.front.view),
3366                },
3367                wgpu::BindGroupEntry {
3368                    binding: 1,
3369                    resource: self
3370                        .target_composition_pipelines
3371                        .secondary_uniform_buffer
3372                        .as_entire_binding(),
3373                },
3374            ],
3375        });
3376        let source_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
3377            label: Some("sim-engine trail source bind group"),
3378            layout: &self.target_composition_pipelines.bind_group_layout,
3379            entries: &[
3380                wgpu::BindGroupEntry {
3381                    binding: 0,
3382                    resource: wgpu::BindingResource::TextureView(&source.view),
3383                },
3384                wgpu::BindGroupEntry {
3385                    binding: 1,
3386                    resource: self
3387                        .target_composition_pipelines
3388                        .uniform_buffer
3389                        .as_entire_binding(),
3390                },
3391            ],
3392        });
3393        let upload = upload_started_at.elapsed();
3394        let encode_started_at = Instant::now();
3395        let mut encoder = self
3396            .device
3397            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3398                label: Some("sim-engine trail accumulation encoder"),
3399            });
3400        {
3401            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
3402                label: Some("sim-engine trail history pass"),
3403                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
3404                    view: &trails.back.view,
3405                    depth_slice: None,
3406                    resolve_target: None,
3407                    ops: wgpu::Operations {
3408                        load: wgpu::LoadOp::Clear(Color::rgba(0.0, 0.0, 0.0, 0.0).to_wgpu()),
3409                        store: wgpu::StoreOp::Store,
3410                    },
3411                })],
3412                depth_stencil_attachment: None,
3413                timestamp_writes: None,
3414                occlusion_query_set: None,
3415                multiview_mask: None,
3416            });
3417            pass.set_pipeline(&self.target_composition_pipelines.alpha);
3418            pass.set_bind_group(0, &history_bind_group, &[]);
3419            pass.draw(0..6, 0..1);
3420        }
3421        {
3422            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
3423                label: Some("sim-engine trail source pass"),
3424                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
3425                    view: &trails.back.view,
3426                    depth_slice: None,
3427                    resolve_target: None,
3428                    ops: wgpu::Operations {
3429                        load: wgpu::LoadOp::Load,
3430                        store: wgpu::StoreOp::Store,
3431                    },
3432                })],
3433                depth_stencil_attachment: None,
3434                timestamp_writes: None,
3435                occlusion_query_set: None,
3436                multiview_mask: None,
3437            });
3438            pass.set_pipeline(self.target_composition_pipelines.pipeline(source_blend));
3439            pass.set_bind_group(0, &source_bind_group, &[]);
3440            pass.draw(0..6, 0..1);
3441        }
3442        self.queue.submit([encoder.finish()]);
3443        std::mem::swap(&mut trails.front, &mut trails.back);
3444        render_report(
3445            RenderStatus::Drawn,
3446            Duration::ZERO,
3447            upload,
3448            Duration::ZERO,
3449            Duration::ZERO,
3450            encode_started_at.elapsed(),
3451            frame_started_at.elapsed(),
3452            false,
3453            true,
3454            TessellationStats::default(),
3455        )
3456    }
3457
3458    fn draw_clear_trail_buffer(
3459        &self,
3460        trails: &TrailBuffer2d,
3461        color: Color,
3462        frame_started_at: Instant,
3463    ) -> RenderReport {
3464        let encode_started_at = Instant::now();
3465        let mut encoder = self
3466            .device
3467            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3468                label: Some("sim-engine trail clear encoder"),
3469            });
3470        for view in [&trails.front.view, &trails.back.view] {
3471            let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
3472                label: Some("sim-engine trail clear pass"),
3473                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
3474                    view,
3475                    depth_slice: None,
3476                    resolve_target: None,
3477                    ops: wgpu::Operations {
3478                        load: wgpu::LoadOp::Clear(premultiplied_wgpu_color(color)),
3479                        store: wgpu::StoreOp::Store,
3480                    },
3481                })],
3482                depth_stencil_attachment: None,
3483                timestamp_writes: None,
3484                occlusion_query_set: None,
3485                multiview_mask: None,
3486            });
3487        }
3488        self.queue.submit([encoder.finish()]);
3489        render_report(
3490            RenderStatus::Drawn,
3491            Duration::ZERO,
3492            Duration::ZERO,
3493            Duration::ZERO,
3494            Duration::ZERO,
3495            encode_started_at.elapsed(),
3496            frame_started_at.elapsed(),
3497            false,
3498            true,
3499            TessellationStats::default(),
3500        )
3501    }
3502
3503    fn prepare_particle_draw(
3504        &self,
3505        field: &mut ParticleField2d,
3506        camera: Camera2d,
3507    ) -> Result<ParticleDrawPreparation, RendererFrameError> {
3508        let (logical_width, logical_height) = self.logical_size();
3509        let viewport = LogicalViewport::new(logical_width, logical_height)
3510            .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
3511        let Some(camera_uniform) = CameraUniform::new(camera, viewport) else {
3512            return Err(RendererFrameError::InvalidGeometryTransform);
3513        };
3514        let instance_count = field.instances.len();
3515        let visibility_checked = instance_count.min(field.budget.max_visibility_checks_per_frame);
3516        if visibility_checked < instance_count {
3517            field.visible_instances.clear();
3518            for candidate_index in 0..visibility_checked {
3519                let source_index =
3520                    uniformly_sampled_index(candidate_index, instance_count, visibility_checked);
3521                let instance = field.instances[source_index];
3522                if !instance.is_safe_for(camera_uniform) {
3523                    return Err(RendererFrameError::InvalidGeometryTransform);
3524                }
3525                if instance.intersects_viewport(camera_uniform, viewport) {
3526                    field.visible_instances.push(instance);
3527                }
3528            }
3529            let visible_count = field.visible_instances.len();
3530            let selected_count = visible_count.min(field.budget.instance_limit());
3531            if selected_count < visible_count {
3532                let mut visible_index = 0;
3533                field.visible_instances.retain(|_| {
3534                    let selected = particle_visible_index_is_selected(
3535                        visible_index,
3536                        visible_count,
3537                        selected_count,
3538                    );
3539                    visible_index += 1;
3540                    selected
3541                });
3542            }
3543            field.statistics = particle_statistics_with_budget(
3544                instance_count,
3545                visibility_checked,
3546                visible_count,
3547                selected_count,
3548                0,
3549            );
3550            return self.upload_particle_draw(field, camera_uniform, selected_count);
3551        }
3552
3553        let visible_count = visible_particle_count(&field.instances, camera_uniform, viewport)?;
3554        let selected_count = visible_count.min(field.budget.instance_limit());
3555        field.statistics = particle_statistics_with_budget(
3556            instance_count,
3557            instance_count,
3558            visible_count,
3559            selected_count,
3560            0,
3561        );
3562        if selected_count == field.instances.len() {
3563            field.visible_instances.clear();
3564        } else {
3565            field.visible_instances.clear();
3566            let mut visible_index = 0;
3567            for instance in field.instances.iter().copied() {
3568                if !instance.intersects_viewport(camera_uniform, viewport) {
3569                    continue;
3570                }
3571                let selected_index = field.visible_instances.len();
3572                if selected_index < selected_count
3573                    && particle_visible_index_is_selected(
3574                        visible_index,
3575                        visible_count,
3576                        selected_count,
3577                    )
3578                {
3579                    field.visible_instances.push(instance);
3580                }
3581                visible_index += 1;
3582            }
3583        }
3584        self.upload_particle_draw(field, camera_uniform, selected_count)
3585    }
3586
3587    fn upload_particle_draw(
3588        &self,
3589        field: &ParticleField2d,
3590        camera_uniform: CameraUniform,
3591        visible_count: usize,
3592    ) -> Result<ParticleDrawPreparation, RendererFrameError> {
3593        let visible_instances =
3594            if field.visible_instances.is_empty() && visible_count == field.instances.len() {
3595                field.instances.as_slice()
3596            } else {
3597                field.visible_instances.as_slice()
3598            };
3599        let upload_started_at = Instant::now();
3600        if !visible_instances.is_empty() {
3601            self.queue.write_buffer(
3602                &field.instance_buffer,
3603                0,
3604                bytemuck::cast_slice(visible_instances),
3605            );
3606        }
3607        let upload = upload_started_at.elapsed();
3608        let camera_uniform_upload_started_at = Instant::now();
3609        self.queue.write_buffer(
3610            &self.camera_uniform_buffer,
3611            0,
3612            bytemuck::bytes_of(&camera_uniform),
3613        );
3614        let camera_uniform_upload = camera_uniform_upload_started_at.elapsed();
3615
3616        Ok(ParticleDrawPreparation {
3617            visible_count,
3618            upload,
3619            camera_uniform_upload,
3620        })
3621    }
3622
3623    fn draw_particle_field(
3624        &mut self,
3625        background: Color,
3626        field: &mut ParticleField2d,
3627        camera: Camera2d,
3628        frame_started_at: Instant,
3629    ) -> Result<RenderReport, RendererFrameError> {
3630        let preparation = self.prepare_particle_draw(field, camera)?;
3631
3632        let surface_acquire_started_at = Instant::now();
3633        let surface_texture = match self.surface.get_current_texture() {
3634            wgpu::CurrentSurfaceTexture::Success(texture)
3635            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
3636            wgpu::CurrentSurfaceTexture::Timeout => {
3637                return Ok(render_report(
3638                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
3639                    Duration::ZERO,
3640                    preparation.upload,
3641                    preparation.camera_uniform_upload,
3642                    surface_acquire_started_at.elapsed(),
3643                    Duration::ZERO,
3644                    frame_started_at.elapsed(),
3645                    false,
3646                    true,
3647                    TessellationStats::default(),
3648                ));
3649            }
3650            wgpu::CurrentSurfaceTexture::Occluded => {
3651                return Ok(render_report(
3652                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
3653                    Duration::ZERO,
3654                    preparation.upload,
3655                    preparation.camera_uniform_upload,
3656                    surface_acquire_started_at.elapsed(),
3657                    Duration::ZERO,
3658                    frame_started_at.elapsed(),
3659                    false,
3660                    true,
3661                    TessellationStats::default(),
3662                ));
3663            }
3664            wgpu::CurrentSurfaceTexture::Outdated => {
3665                self.resize(self.config.width, self.config.height);
3666                return Ok(render_report(
3667                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
3668                    Duration::ZERO,
3669                    preparation.upload,
3670                    preparation.camera_uniform_upload,
3671                    surface_acquire_started_at.elapsed(),
3672                    Duration::ZERO,
3673                    frame_started_at.elapsed(),
3674                    false,
3675                    true,
3676                    TessellationStats::default(),
3677                ));
3678            }
3679            wgpu::CurrentSurfaceTexture::Lost => {
3680                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
3681            }
3682            wgpu::CurrentSurfaceTexture::Validation => {
3683                return Err(RendererFrameError::Surface(
3684                    RendererSurfaceStatus::Validation,
3685                ));
3686            }
3687        };
3688        let surface_acquire = surface_acquire_started_at.elapsed();
3689        let encode_submit_present_started_at = Instant::now();
3690        let surface_view = surface_texture
3691            .texture
3692            .create_view(&wgpu::TextureViewDescriptor::default());
3693        let (view, resolve_target) = match &self.multisample_target {
3694            Some(target) => (&target.view, Some(&surface_view)),
3695            None => (&surface_view, None),
3696        };
3697        let mut encoder = self
3698            .device
3699            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3700                label: Some("sim-engine particle render encoder"),
3701            });
3702        {
3703            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
3704                label: Some("sim-engine particle render pass"),
3705                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
3706                    view,
3707                    depth_slice: None,
3708                    resolve_target,
3709                    ops: wgpu::Operations {
3710                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
3711                        store: wgpu::StoreOp::Store,
3712                    },
3713                })],
3714                depth_stencil_attachment: None,
3715                timestamp_writes: None,
3716                occlusion_query_set: None,
3717                multiview_mask: None,
3718            });
3719            if preparation.visible_count > 0 {
3720                pass.set_pipeline(&self.particle_pipeline);
3721                pass.set_bind_group(0, &self.camera_bind_group, &[]);
3722                pass.set_vertex_buffer(0, self.particle_unit_buffer.slice(..));
3723                pass.set_vertex_buffer(1, field.instance_buffer.slice(..));
3724                pass.draw(0..6, 0..preparation.visible_count as u32);
3725            }
3726        }
3727        self.queue.submit([encoder.finish()]);
3728        self.queue.present(surface_texture);
3729        field.statistics.rendered = preparation.visible_count;
3730        Ok(render_report(
3731            RenderStatus::Drawn,
3732            Duration::ZERO,
3733            preparation.upload,
3734            preparation.camera_uniform_upload,
3735            surface_acquire,
3736            encode_submit_present_started_at.elapsed(),
3737            frame_started_at.elapsed(),
3738            false,
3739            true,
3740            TessellationStats::default(),
3741        ))
3742    }
3743
3744    fn draw_particle_field_to_target(
3745        &self,
3746        target: &RenderTarget2d,
3747        field: &mut ParticleField2d,
3748        camera: Camera2d,
3749        load: RenderTargetLoad,
3750        frame_started_at: Instant,
3751    ) -> Result<RenderReport, RendererFrameError> {
3752        let preparation = self.prepare_particle_draw(field, camera)?;
3753        let encode_started_at = Instant::now();
3754        let mut encoder = self
3755            .device
3756            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
3757                label: Some("sim-engine target particle encoder"),
3758            });
3759        {
3760            let load = match load {
3761                RenderTargetLoad::Load => wgpu::LoadOp::Load,
3762                RenderTargetLoad::Clear(color) => {
3763                    wgpu::LoadOp::Clear(premultiplied_wgpu_color(color))
3764                }
3765            };
3766            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
3767                label: Some("sim-engine target particle pass"),
3768                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
3769                    view: &target.view,
3770                    depth_slice: None,
3771                    resolve_target: None,
3772                    ops: wgpu::Operations {
3773                        load,
3774                        store: wgpu::StoreOp::Store,
3775                    },
3776                })],
3777                depth_stencil_attachment: None,
3778                timestamp_writes: None,
3779                occlusion_query_set: None,
3780                multiview_mask: None,
3781            });
3782            if preparation.visible_count > 0 {
3783                pass.set_pipeline(&self.target_particle_pipeline);
3784                pass.set_bind_group(0, &self.camera_bind_group, &[]);
3785                pass.set_vertex_buffer(0, self.particle_unit_buffer.slice(..));
3786                pass.set_vertex_buffer(1, field.instance_buffer.slice(..));
3787                pass.draw(0..6, 0..preparation.visible_count as u32);
3788            }
3789        }
3790        self.queue.submit([encoder.finish()]);
3791        field.statistics.rendered = preparation.visible_count;
3792        Ok(render_report(
3793            RenderStatus::Drawn,
3794            Duration::ZERO,
3795            preparation.upload,
3796            preparation.camera_uniform_upload,
3797            Duration::ZERO,
3798            encode_started_at.elapsed(),
3799            frame_started_at.elapsed(),
3800            false,
3801            true,
3802            TessellationStats::default(),
3803        ))
3804    }
3805
3806    fn ensure_vertex_capacity(&mut self, vertex_count: usize) -> Result<(), RendererFrameError> {
3807        if vertex_count <= self.vertex_capacity {
3808            return Ok(());
3809        }
3810
3811        self.vertex_capacity = dynamic_vertex_capacity(vertex_count)
3812            .filter(|capacity| buffer_capacity_fits::<Vertex>(&self.device, *capacity))
3813            .ok_or(RendererFrameError::GeometryCapacityTooLarge)?;
3814        self.vertex_buffer = Arc::new(create_vertex_buffer(&self.device, self.vertex_capacity));
3815        Ok(())
3816    }
3817
3818    fn validate_dynamic_mesh(&self, mesh: &DynamicMesh2d) -> Result<(), DynamicMeshError> {
3819        prepared_scene_belongs_to(&self.renderer_identity, &mesh.renderer_identity)
3820            .then_some(())
3821            .ok_or(DynamicMeshError::RendererMismatch)
3822    }
3823
3824    fn validate_particle_field(&self, field: &ParticleField2d) -> Result<(), ParticleFieldError> {
3825        prepared_scene_belongs_to(&self.renderer_identity, &field.renderer_identity)
3826            .then_some(())
3827            .ok_or(ParticleFieldError::RendererMismatch)
3828    }
3829
3830    fn validate_scalar_field_texture(
3831        &self,
3832        texture: &ScalarFieldTexture,
3833    ) -> Result<(), ScalarFieldTextureError> {
3834        prepared_scene_belongs_to(&self.renderer_identity, &texture.renderer_identity)
3835            .then_some(())
3836            .ok_or(ScalarFieldTextureError::RendererMismatch)
3837    }
3838
3839    fn color_map_view(&mut self, color_map: &ColorMap) -> wgpu::TextureView {
3840        if let Some(cached) = self
3841            .color_map_cache
3842            .as_ref()
3843            .filter(|cached| cached.source == *color_map)
3844        {
3845            return cached.view.clone();
3846        }
3847        let cached = create_cached_color_map(&self.device, &self.queue, color_map);
3848        let view = cached.view.clone();
3849        self.color_map_cache = Some(cached);
3850        view
3851    }
3852
3853    fn validate_render_target(&self, target: &RenderTarget2d) -> Result<(), RenderTargetError> {
3854        prepared_scene_belongs_to(&self.renderer_identity, &target.renderer_identity)
3855            .then_some(())
3856            .ok_or(RenderTargetError::RendererMismatch)
3857    }
3858
3859    fn validate_trail_buffer(&self, trails: &TrailBuffer2d) -> Result<(), RenderTargetError> {
3860        prepared_scene_belongs_to(&self.renderer_identity, &trails.renderer_identity)
3861            .then_some(())
3862            .ok_or(RenderTargetError::RendererMismatch)
3863    }
3864}
3865
3866fn prepared_scene_belongs_to(renderer_identity: &Arc<()>, scene_identity: &Arc<()>) -> bool {
3867    Arc::ptr_eq(renderer_identity, scene_identity)
3868}
3869
3870fn render_target_allocation_bytes(
3871    format: wgpu::TextureFormat,
3872    width: u32,
3873    height: u32,
3874) -> Option<usize> {
3875    let bytes_per_texel = u64::from(format.block_copy_size(None)?);
3876    let byte_count = u64::from(width)
3877        .checked_mul(u64::from(height))?
3878        .checked_mul(bytes_per_texel)?;
3879    usize::try_from(byte_count).ok()
3880}
3881
3882fn dynamic_vertices_to_gpu(
3883    vertices: &[DynamicVertex2d],
3884) -> Result<Vec<DynamicGpu>, DynamicMeshError> {
3885    validate_dynamic_vertices(vertices)?;
3886    Ok(vertices
3887        .iter()
3888        .copied()
3889        .map(dynamic_vertex_to_gpu)
3890        .collect())
3891}
3892
3893fn validate_dynamic_vertices(vertices: &[DynamicVertex2d]) -> Result<(), DynamicMeshError> {
3894    if !vertices.len().is_multiple_of(3) {
3895        return Err(DynamicMeshError::InvalidVertexCount);
3896    }
3897    // Private fields and the only public constructor make finiteness an
3898    // invariant of DynamicVertex2d. Keep the assertion in development without
3899    // rescanning an already-validated high-volume stream in release builds.
3900    debug_assert!(vertices.iter().all(|vertex| {
3901        vertex.world_position.is_finite()
3902            && vertex.depth.is_finite()
3903            && vertex.color.is_normalized()
3904    }));
3905    Ok(())
3906}
3907
3908fn dynamic_vertex_to_gpu(vertex: DynamicVertex2d) -> DynamicGpu {
3909    DynamicGpu {
3910        world_position: [vertex.world_position.x, vertex.world_position.y],
3911        depth: vertex.depth,
3912        color: vertex.color.to_array(),
3913    }
3914}
3915
3916fn dynamic_vertex_capacity(vertex_count: usize) -> Option<usize> {
3917    vertex_count.max(1).checked_next_power_of_two()
3918}
3919
3920fn particle_instances_to_gpu(
3921    instances: &[ParticleInstance2d],
3922) -> Result<Vec<ParticleGpu>, ParticleFieldError> {
3923    instances
3924        .iter()
3925        .copied()
3926        .map(|instance| {
3927            let world_position = instance.world_position();
3928            let radius = instance.radius();
3929            let color = instance.color();
3930            let depth = instance.depth();
3931            if !world_position.is_finite()
3932                || !radius.is_finite()
3933                || radius <= 0.0
3934                || !color.is_normalized()
3935                || !depth.is_finite()
3936            {
3937                return Err(ParticleFieldError::InvalidInstance);
3938            }
3939            Ok(ParticleGpu {
3940                world_position: [world_position.x, world_position.y],
3941                depth,
3942                radius,
3943                color: color.to_array(),
3944            })
3945        })
3946        .collect()
3947}
3948
3949fn particle_instance_capacity(instance_count: usize) -> Option<usize> {
3950    instance_count.max(1).checked_next_power_of_two()
3951}
3952
3953fn particle_budgeted_capacity(
3954    instance_count: usize,
3955    budget: ParticleRenderBudget,
3956) -> Option<usize> {
3957    let limit = budget.instance_limit();
3958    let required = instance_count.min(limit).max(1);
3959    particle_instance_capacity(required).map(|capacity| capacity.min(limit))
3960}
3961
3962fn buffer_allocation_bytes<T>(capacity: usize) -> Option<u64> {
3963    u64::try_from(capacity)
3964        .ok()?
3965        .checked_mul(std::mem::size_of::<T>() as u64)
3966}
3967
3968fn buffer_capacity_fits<T>(device: &wgpu::Device, capacity: usize) -> bool {
3969    buffer_allocation_bytes::<T>(capacity)
3970        .is_some_and(|bytes| bytes <= device.limits().max_buffer_size)
3971}
3972
3973fn particle_update_range(
3974    first_instance: usize,
3975    replacement_count: usize,
3976    current_count: usize,
3977) -> Result<Range<usize>, ParticleFieldError> {
3978    let end = first_instance
3979        .checked_add(replacement_count)
3980        .ok_or(ParticleFieldError::UpdateRangeOutOfBounds)?;
3981    (end <= current_count)
3982        .then_some(first_instance..end)
3983        .ok_or(ParticleFieldError::UpdateRangeOutOfBounds)
3984}
3985
3986#[cfg(test)]
3987fn visible_particle_instances(
3988    instances: &[ParticleGpu],
3989    camera: CameraUniform,
3990    viewport: LogicalViewport,
3991) -> Result<Vec<ParticleGpu>, RendererFrameError> {
3992    visible_particle_count(instances, camera, viewport)?;
3993    Ok(instances
3994        .iter()
3995        .copied()
3996        .filter(|instance| instance.intersects_viewport(camera, viewport))
3997        .collect())
3998}
3999
4000fn visible_particle_count(
4001    instances: &[ParticleGpu],
4002    camera: CameraUniform,
4003    viewport: LogicalViewport,
4004) -> Result<usize, RendererFrameError> {
4005    let mut visible = 0;
4006    for instance in instances.iter().copied() {
4007        if !instance.is_safe_for(camera) {
4008            return Err(RendererFrameError::InvalidGeometryTransform);
4009        }
4010        visible += usize::from(instance.intersects_viewport(camera, viewport));
4011    }
4012    Ok(visible)
4013}
4014
4015fn particle_visible_index_is_selected(
4016    visible_index: usize,
4017    visible_count: usize,
4018    selected_count: usize,
4019) -> bool {
4020    if visible_count == 0 || selected_count == 0 {
4021        return false;
4022    }
4023    let before = visible_index as u128 * selected_count as u128 / visible_count as u128;
4024    let after = (visible_index as u128 + 1) * selected_count as u128 / visible_count as u128;
4025    before < after
4026}
4027
4028fn uniformly_sampled_index(sample_index: usize, source_count: usize, sample_count: usize) -> usize {
4029    debug_assert!(sample_index < sample_count);
4030    debug_assert!(sample_count <= source_count);
4031    (((sample_index as u128 + 1) * source_count as u128 - 1) / sample_count as u128) as usize
4032}
4033
4034fn particle_statistics(
4035    instance_count: usize,
4036    visible: usize,
4037    rendered: usize,
4038) -> ParticleStatistics {
4039    particle_statistics_with_budget(instance_count, instance_count, visible, visible, rendered)
4040}
4041
4042fn particle_statistics_with_budget(
4043    instance_count: usize,
4044    visibility_checked: usize,
4045    visible: usize,
4046    selected: usize,
4047    rendered: usize,
4048) -> ParticleStatistics {
4049    ParticleStatistics {
4050        submitted: instance_count,
4051        visibility_checked,
4052        visible,
4053        culled: visibility_checked.saturating_sub(visible),
4054        budget_limited: instance_count
4055            .saturating_sub(visibility_checked)
4056            .saturating_add(visible.saturating_sub(selected)),
4057        dropped: 0,
4058        rendered,
4059    }
4060}
4061
4062fn prepare_scene_resources(
4063    device: &wgpu::Device,
4064    queue: &wgpu::Queue,
4065    renderer_identity: Arc<()>,
4066    scene: &Scene,
4067) -> Result<PreparedScene, PreparedSceneError> {
4068    let mut vertices = Vec::new();
4069    let mut draw_batches = Vec::new();
4070    let tessellation = tessellate_scene(scene, &mut vertices, &mut draw_batches);
4071    let geometry_extents = GeometryExtents::from_vertices(&vertices);
4072    if !buffer_capacity_fits::<Vertex>(device, vertices.len().max(1)) {
4073        return Err(PreparedSceneError::CapacityTooLarge);
4074    }
4075    let vertex_buffer = Arc::new(create_vertex_buffer(device, vertices.len()));
4076    if !vertices.is_empty() {
4077        queue.write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(&vertices));
4078    }
4079    let vertex_count = vertices.len();
4080    let vertices: Arc<[Vertex]> = vertices.into();
4081
4082    Ok(PreparedScene {
4083        renderer_identity,
4084        background: scene.background(),
4085        vertex_buffer,
4086        vertices,
4087        command_count: scene.command_count(),
4088        vertex_count,
4089        geometry_extents,
4090        draw_batches,
4091        tessellation,
4092    })
4093}
4094
4095fn restore_prepared_scene_resources(
4096    device: &wgpu::Device,
4097    queue: &wgpu::Queue,
4098    renderer_identity: Arc<()>,
4099    source: &PreparedScene,
4100) -> Result<PreparedScene, PreparedSceneError> {
4101    if !buffer_capacity_fits::<Vertex>(device, source.vertices.len().max(1)) {
4102        return Err(PreparedSceneError::CapacityTooLarge);
4103    }
4104    let vertex_buffer = Arc::new(create_vertex_buffer(device, source.vertices.len()));
4105    if !source.vertices.is_empty() {
4106        queue.write_buffer(
4107            &vertex_buffer,
4108            0,
4109            bytemuck::cast_slice(source.vertices.as_ref()),
4110        );
4111    }
4112
4113    Ok(PreparedScene {
4114        renderer_identity,
4115        background: source.background,
4116        vertex_buffer,
4117        vertices: Arc::clone(&source.vertices),
4118        command_count: source.command_count,
4119        vertex_count: source.vertex_count,
4120        geometry_extents: source.geometry_extents,
4121        draw_batches: source.draw_batches.clone(),
4122        tessellation: source.tessellation,
4123    })
4124}
4125
4126fn restore_dynamic_mesh_resources(
4127    device: &wgpu::Device,
4128    queue: &wgpu::Queue,
4129    renderer_identity: Arc<()>,
4130    source: &DynamicMesh2d,
4131) -> Result<DynamicMesh2d, DynamicMeshError> {
4132    if !buffer_capacity_fits::<DynamicGpu>(device, source.vertex_capacity) {
4133        return Err(DynamicMeshError::CapacityTooLarge);
4134    }
4135    let vertex_buffer = Arc::new(create_dynamic_vertex_buffer(device, source.vertex_capacity));
4136    if !source.vertices.is_empty() {
4137        queue.write_buffer(
4138            &vertex_buffer,
4139            0,
4140            bytemuck::cast_slice(source.vertices.as_slice()),
4141        );
4142    }
4143    Ok(DynamicMesh2d {
4144        renderer_identity,
4145        vertex_buffer,
4146        vertices: source.vertices.clone(),
4147        vertex_capacity: source.vertex_capacity,
4148        geometry_extents: source.geometry_extents,
4149    })
4150}
4151
4152fn restore_particle_field_resources(
4153    device: &wgpu::Device,
4154    _queue: &wgpu::Queue,
4155    renderer_identity: Arc<()>,
4156    source: &ParticleField2d,
4157) -> Result<ParticleField2d, ParticleFieldError> {
4158    if !buffer_capacity_fits::<ParticleGpu>(device, source.instance_capacity) {
4159        return Err(ParticleFieldError::CapacityTooLarge);
4160    }
4161    let instance_buffer = Arc::new(create_particle_instance_buffer(
4162        device,
4163        source.instance_capacity,
4164    ));
4165    Ok(ParticleField2d {
4166        renderer_identity,
4167        instance_buffer,
4168        instances: source.instances.clone(),
4169        visible_instances: Vec::new(),
4170        instance_capacity: source.instance_capacity,
4171        budget: source.budget,
4172        statistics: particle_statistics(source.instances.len(), source.instances.len(), 0),
4173    })
4174}
4175
4176#[allow(clippy::too_many_arguments)]
4177fn render_report(
4178    status: RenderStatus,
4179    tessellation: Duration,
4180    upload: Duration,
4181    camera_uniform_upload: Duration,
4182    surface_acquire: Duration,
4183    encode_submit_present: Duration,
4184    total_cpu: Duration,
4185    geometry_reused: bool,
4186    geometry_streamed: bool,
4187    tessellation_stats: TessellationStats,
4188) -> RenderReport {
4189    RenderReport {
4190        status,
4191        metrics: RendererFrameMetrics {
4192            tessellation,
4193            upload,
4194            camera_uniform_upload,
4195            surface_acquire,
4196            encode_submit_present,
4197            total_cpu,
4198            geometry_reused,
4199            geometry_streamed,
4200            tessellation_stats,
4201        },
4202    }
4203}
4204
4205fn create_pipeline(
4206    device: &wgpu::Device,
4207    format: wgpu::TextureFormat,
4208    sample_count: u32,
4209) -> (
4210    wgpu::RenderPipeline,
4211    wgpu::RenderPipeline,
4212    wgpu::RenderPipeline,
4213    wgpu::RenderPipeline,
4214    wgpu::RenderPipeline,
4215    wgpu::RenderPipeline,
4216    CompositionPipelines,
4217    CompositionPipelines,
4218    wgpu::Buffer,
4219    wgpu::BindGroup,
4220    wgpu::Buffer,
4221    wgpu::BindGroupLayout,
4222) {
4223    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
4224        label: Some("sim-engine flat color shader"),
4225        source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("primitive.wgsl"))),
4226    });
4227    let camera_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
4228        label: Some("sim-engine camera uniform buffer"),
4229        size: std::mem::size_of::<CameraUniform>() as wgpu::BufferAddress,
4230        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
4231        mapped_at_creation: false,
4232    });
4233    let camera_bind_group_layout =
4234        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
4235            label: Some("sim-engine camera bind group layout"),
4236            entries: &[wgpu::BindGroupLayoutEntry {
4237                binding: 0,
4238                visibility: wgpu::ShaderStages::VERTEX,
4239                ty: wgpu::BindingType::Buffer {
4240                    ty: wgpu::BufferBindingType::Uniform,
4241                    has_dynamic_offset: false,
4242                    min_binding_size: None,
4243                },
4244                count: None,
4245            }],
4246        });
4247    let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
4248        label: Some("sim-engine camera bind group"),
4249        layout: &camera_bind_group_layout,
4250        entries: &[wgpu::BindGroupEntry {
4251            binding: 0,
4252            resource: camera_uniform_buffer.as_entire_binding(),
4253        }],
4254    });
4255    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
4256        label: Some("sim-engine shape pipeline layout"),
4257        bind_group_layouts: &[Some(&camera_bind_group_layout)],
4258        immediate_size: 0,
4259    });
4260    let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
4261        label: Some("sim-engine shape pipeline"),
4262        layout: Some(&pipeline_layout),
4263        vertex: wgpu::VertexState {
4264            module: &shader,
4265            entry_point: Some("vs_main"),
4266            compilation_options: wgpu::PipelineCompilationOptions::default(),
4267            buffers: &[Some(Vertex::LAYOUT)],
4268        },
4269        primitive: wgpu::PrimitiveState {
4270            topology: wgpu::PrimitiveTopology::TriangleList,
4271            ..Default::default()
4272        },
4273        depth_stencil: None,
4274        multisample: wgpu::MultisampleState {
4275            count: sample_count,
4276            ..Default::default()
4277        },
4278        fragment: Some(wgpu::FragmentState {
4279            module: &shader,
4280            entry_point: Some("fs_main"),
4281            compilation_options: wgpu::PipelineCompilationOptions::default(),
4282            targets: &[Some(wgpu::ColorTargetState {
4283                format,
4284                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
4285                write_mask: wgpu::ColorWrites::ALL,
4286            })],
4287        }),
4288        multiview_mask: None,
4289        cache: None,
4290    });
4291
4292    let dynamic_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
4293        label: Some("sim-engine dynamic mesh pipeline"),
4294        layout: Some(&pipeline_layout),
4295        vertex: wgpu::VertexState {
4296            module: &shader,
4297            entry_point: Some("dynamic_vs_main"),
4298            compilation_options: wgpu::PipelineCompilationOptions::default(),
4299            buffers: &[Some(DynamicGpu::LAYOUT)],
4300        },
4301        primitive: wgpu::PrimitiveState {
4302            topology: wgpu::PrimitiveTopology::TriangleList,
4303            ..Default::default()
4304        },
4305        depth_stencil: None,
4306        multisample: wgpu::MultisampleState {
4307            count: sample_count,
4308            ..Default::default()
4309        },
4310        fragment: Some(wgpu::FragmentState {
4311            module: &shader,
4312            entry_point: Some("fs_main"),
4313            compilation_options: wgpu::PipelineCompilationOptions::default(),
4314            targets: &[Some(wgpu::ColorTargetState {
4315                format,
4316                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
4317                write_mask: wgpu::ColorWrites::ALL,
4318            })],
4319        }),
4320        multiview_mask: None,
4321        cache: None,
4322    });
4323
4324    let particle_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
4325        label: Some("sim-engine particle pipeline"),
4326        layout: Some(&pipeline_layout),
4327        vertex: wgpu::VertexState {
4328            module: &shader,
4329            entry_point: Some("particle_vs_main"),
4330            compilation_options: wgpu::PipelineCompilationOptions::default(),
4331            buffers: &[Some(ParticleUnitVertex::LAYOUT), Some(ParticleGpu::LAYOUT)],
4332        },
4333        primitive: wgpu::PrimitiveState {
4334            topology: wgpu::PrimitiveTopology::TriangleList,
4335            ..Default::default()
4336        },
4337        depth_stencil: None,
4338        multisample: wgpu::MultisampleState {
4339            count: sample_count,
4340            ..Default::default()
4341        },
4342        fragment: Some(wgpu::FragmentState {
4343            module: &shader,
4344            entry_point: Some("fs_main"),
4345            compilation_options: wgpu::PipelineCompilationOptions::default(),
4346            targets: &[Some(wgpu::ColorTargetState {
4347                format,
4348                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
4349                write_mask: wgpu::ColorWrites::ALL,
4350            })],
4351        }),
4352        multiview_mask: None,
4353        cache: None,
4354    });
4355
4356    let target_particle_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
4357        label: Some("sim-engine target particle pipeline"),
4358        layout: Some(&pipeline_layout),
4359        vertex: wgpu::VertexState {
4360            module: &shader,
4361            entry_point: Some("particle_vs_main"),
4362            compilation_options: wgpu::PipelineCompilationOptions::default(),
4363            buffers: &[Some(ParticleUnitVertex::LAYOUT), Some(ParticleGpu::LAYOUT)],
4364        },
4365        primitive: wgpu::PrimitiveState {
4366            topology: wgpu::PrimitiveTopology::TriangleList,
4367            ..Default::default()
4368        },
4369        depth_stencil: None,
4370        multisample: wgpu::MultisampleState {
4371            count: 1,
4372            ..Default::default()
4373        },
4374        fragment: Some(wgpu::FragmentState {
4375            module: &shader,
4376            entry_point: Some("fs_main"),
4377            compilation_options: wgpu::PipelineCompilationOptions::default(),
4378            targets: &[Some(wgpu::ColorTargetState {
4379                format,
4380                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
4381                write_mask: wgpu::ColorWrites::ALL,
4382            })],
4383        }),
4384        multiview_mask: None,
4385        cache: None,
4386    });
4387
4388    let heatmap_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
4389        label: Some("sim-engine heatmap uniform buffer"),
4390        size: std::mem::size_of::<HeatmapUniform>() as wgpu::BufferAddress,
4391        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
4392        mapped_at_creation: false,
4393    });
4394    let heatmap_bind_group_layout =
4395        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
4396            label: Some("sim-engine heatmap bind group layout"),
4397            entries: &[
4398                wgpu::BindGroupLayoutEntry {
4399                    binding: 0,
4400                    visibility: wgpu::ShaderStages::FRAGMENT,
4401                    ty: wgpu::BindingType::Texture {
4402                        multisampled: false,
4403                        view_dimension: wgpu::TextureViewDimension::D2,
4404                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
4405                    },
4406                    count: None,
4407                },
4408                wgpu::BindGroupLayoutEntry {
4409                    binding: 1,
4410                    visibility: wgpu::ShaderStages::FRAGMENT,
4411                    ty: wgpu::BindingType::Texture {
4412                        multisampled: false,
4413                        view_dimension: wgpu::TextureViewDimension::D2,
4414                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
4415                    },
4416                    count: None,
4417                },
4418                wgpu::BindGroupLayoutEntry {
4419                    binding: 2,
4420                    visibility: wgpu::ShaderStages::FRAGMENT,
4421                    ty: wgpu::BindingType::Buffer {
4422                        ty: wgpu::BufferBindingType::Uniform,
4423                        has_dynamic_offset: false,
4424                        min_binding_size: None,
4425                    },
4426                    count: None,
4427                },
4428            ],
4429        });
4430    let heatmap_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
4431        label: Some("sim-engine heatmap pipeline layout"),
4432        bind_group_layouts: &[Some(&heatmap_bind_group_layout)],
4433        immediate_size: 0,
4434    });
4435    let heatmap_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
4436        label: Some("sim-engine heatmap pipeline"),
4437        layout: Some(&heatmap_pipeline_layout),
4438        vertex: wgpu::VertexState {
4439            module: &shader,
4440            entry_point: Some("heatmap_vs_main"),
4441            compilation_options: wgpu::PipelineCompilationOptions::default(),
4442            buffers: &[],
4443        },
4444        primitive: wgpu::PrimitiveState {
4445            topology: wgpu::PrimitiveTopology::TriangleList,
4446            ..Default::default()
4447        },
4448        depth_stencil: None,
4449        multisample: wgpu::MultisampleState {
4450            count: sample_count,
4451            ..Default::default()
4452        },
4453        fragment: Some(wgpu::FragmentState {
4454            module: &shader,
4455            entry_point: Some("heatmap_fs_main"),
4456            compilation_options: wgpu::PipelineCompilationOptions::default(),
4457            targets: &[Some(wgpu::ColorTargetState {
4458                format,
4459                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
4460                write_mask: wgpu::ColorWrites::ALL,
4461            })],
4462        }),
4463        multiview_mask: None,
4464        cache: None,
4465    });
4466
4467    let target_heatmap_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
4468        label: Some("sim-engine render-target heatmap pipeline"),
4469        layout: Some(&heatmap_pipeline_layout),
4470        vertex: wgpu::VertexState {
4471            module: &shader,
4472            entry_point: Some("heatmap_vs_main"),
4473            compilation_options: wgpu::PipelineCompilationOptions::default(),
4474            buffers: &[],
4475        },
4476        primitive: wgpu::PrimitiveState {
4477            topology: wgpu::PrimitiveTopology::TriangleList,
4478            ..Default::default()
4479        },
4480        depth_stencil: None,
4481        multisample: wgpu::MultisampleState::default(),
4482        fragment: Some(wgpu::FragmentState {
4483            module: &shader,
4484            entry_point: Some("heatmap_fs_main"),
4485            compilation_options: wgpu::PipelineCompilationOptions::default(),
4486            targets: &[Some(wgpu::ColorTargetState {
4487                format,
4488                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
4489                write_mask: wgpu::ColorWrites::ALL,
4490            })],
4491        }),
4492        multiview_mask: None,
4493        cache: None,
4494    });
4495
4496    let composition_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
4497        label: Some("sim-engine composition uniform buffer"),
4498        size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
4499        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
4500        mapped_at_creation: false,
4501    });
4502    let composition_secondary_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
4503        label: Some("sim-engine composition secondary uniform buffer"),
4504        size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
4505        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
4506        mapped_at_creation: false,
4507    });
4508    let composition_bind_group_layout =
4509        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
4510            label: Some("sim-engine composition bind group layout"),
4511            entries: &[
4512                wgpu::BindGroupLayoutEntry {
4513                    binding: 0,
4514                    visibility: wgpu::ShaderStages::FRAGMENT,
4515                    ty: wgpu::BindingType::Texture {
4516                        multisampled: false,
4517                        view_dimension: wgpu::TextureViewDimension::D2,
4518                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
4519                    },
4520                    count: None,
4521                },
4522                wgpu::BindGroupLayoutEntry {
4523                    binding: 1,
4524                    visibility: wgpu::ShaderStages::FRAGMENT,
4525                    ty: wgpu::BindingType::Buffer {
4526                        ty: wgpu::BufferBindingType::Uniform,
4527                        has_dynamic_offset: false,
4528                        min_binding_size: None,
4529                    },
4530                    count: None,
4531                },
4532            ],
4533        });
4534    let composition_pipeline_layout =
4535        device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
4536            label: Some("sim-engine composition pipeline layout"),
4537            bind_group_layouts: &[Some(&composition_bind_group_layout)],
4538            immediate_size: 0,
4539        });
4540    let composition_pipelines = CompositionPipelines {
4541        alpha: create_composition_pipeline(
4542            device,
4543            &shader,
4544            &composition_pipeline_layout,
4545            format,
4546            sample_count,
4547            BlendMode::Alpha,
4548        ),
4549        additive: create_composition_pipeline(
4550            device,
4551            &shader,
4552            &composition_pipeline_layout,
4553            format,
4554            sample_count,
4555            BlendMode::Additive,
4556        ),
4557        replace: create_composition_pipeline(
4558            device,
4559            &shader,
4560            &composition_pipeline_layout,
4561            format,
4562            sample_count,
4563            BlendMode::Replace,
4564        ),
4565        uniform_buffer: composition_uniform_buffer,
4566        secondary_uniform_buffer: composition_secondary_uniform_buffer,
4567        bind_group_layout: composition_bind_group_layout,
4568    };
4569    let target_composition_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
4570        label: Some("sim-engine target composition uniform buffer"),
4571        size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
4572        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
4573        mapped_at_creation: false,
4574    });
4575    let target_composition_secondary_uniform_buffer =
4576        device.create_buffer(&wgpu::BufferDescriptor {
4577            label: Some("sim-engine target composition secondary uniform buffer"),
4578            size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
4579            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
4580            mapped_at_creation: false,
4581        });
4582    let target_composition_bind_group_layout =
4583        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
4584            label: Some("sim-engine target composition bind group layout"),
4585            entries: &[
4586                wgpu::BindGroupLayoutEntry {
4587                    binding: 0,
4588                    visibility: wgpu::ShaderStages::FRAGMENT,
4589                    ty: wgpu::BindingType::Texture {
4590                        multisampled: false,
4591                        view_dimension: wgpu::TextureViewDimension::D2,
4592                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
4593                    },
4594                    count: None,
4595                },
4596                wgpu::BindGroupLayoutEntry {
4597                    binding: 1,
4598                    visibility: wgpu::ShaderStages::FRAGMENT,
4599                    ty: wgpu::BindingType::Buffer {
4600                        ty: wgpu::BufferBindingType::Uniform,
4601                        has_dynamic_offset: false,
4602                        min_binding_size: None,
4603                    },
4604                    count: None,
4605                },
4606            ],
4607        });
4608    let target_composition_pipeline_layout =
4609        device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
4610            label: Some("sim-engine target composition pipeline layout"),
4611            bind_group_layouts: &[Some(&target_composition_bind_group_layout)],
4612            immediate_size: 0,
4613        });
4614    let target_composition_pipelines = CompositionPipelines {
4615        alpha: create_composition_pipeline(
4616            device,
4617            &shader,
4618            &target_composition_pipeline_layout,
4619            format,
4620            1,
4621            BlendMode::Alpha,
4622        ),
4623        additive: create_composition_pipeline(
4624            device,
4625            &shader,
4626            &target_composition_pipeline_layout,
4627            format,
4628            1,
4629            BlendMode::Additive,
4630        ),
4631        replace: create_composition_pipeline(
4632            device,
4633            &shader,
4634            &target_composition_pipeline_layout,
4635            format,
4636            1,
4637            BlendMode::Replace,
4638        ),
4639        uniform_buffer: target_composition_uniform_buffer,
4640        secondary_uniform_buffer: target_composition_secondary_uniform_buffer,
4641        bind_group_layout: target_composition_bind_group_layout,
4642    };
4643
4644    (
4645        pipeline,
4646        dynamic_pipeline,
4647        particle_pipeline,
4648        target_particle_pipeline,
4649        heatmap_pipeline,
4650        target_heatmap_pipeline,
4651        composition_pipelines,
4652        target_composition_pipelines,
4653        camera_uniform_buffer,
4654        camera_bind_group,
4655        heatmap_uniform_buffer,
4656        heatmap_bind_group_layout,
4657    )
4658}
4659
4660fn preferred_sample_count(adapter: &wgpu::Adapter, format: wgpu::TextureFormat) -> u32 {
4661    let flags = adapter.get_texture_format_features(format).flags;
4662    if flags.contains(
4663        wgpu::TextureFormatFeatureFlags::MULTISAMPLE_X4
4664            | wgpu::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE,
4665    ) {
4666        PREFERRED_SAMPLE_COUNT
4667    } else {
4668        1
4669    }
4670}
4671
4672fn create_vertex_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
4673    device.create_buffer(&wgpu::BufferDescriptor {
4674        label: Some("sim-engine vertex buffer"),
4675        size: (capacity.max(1) * std::mem::size_of::<Vertex>()) as wgpu::BufferAddress,
4676        usage: wgpu::BufferUsages::VERTEX
4677            | wgpu::BufferUsages::COPY_DST
4678            | wgpu::BufferUsages::COPY_SRC,
4679        mapped_at_creation: false,
4680    })
4681}
4682
4683fn create_dynamic_vertex_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
4684    device.create_buffer(&wgpu::BufferDescriptor {
4685        label: Some("sim-engine dynamic vertex buffer"),
4686        size: (capacity.max(1) * std::mem::size_of::<DynamicGpu>()) as wgpu::BufferAddress,
4687        usage: wgpu::BufferUsages::VERTEX
4688            | wgpu::BufferUsages::COPY_DST
4689            | wgpu::BufferUsages::COPY_SRC,
4690        mapped_at_creation: false,
4691    })
4692}
4693
4694fn scalar_field_extent(field: &ScalarField) -> Result<wgpu::Extent3d, ScalarFieldTextureError> {
4695    let width =
4696        u32::try_from(field.width()).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
4697    let height =
4698        u32::try_from(field.height()).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
4699    let _bytes_per_row = width
4700        .checked_mul(std::mem::size_of::<f32>() as u32)
4701        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
4702    Ok(wgpu::Extent3d {
4703        width,
4704        height,
4705        depth_or_array_layers: 1,
4706    })
4707}
4708
4709fn scalar_value_range_extent(minimum: f32, maximum: f32) -> Option<f32> {
4710    if !minimum.is_finite() || !maximum.is_finite() || maximum <= minimum {
4711        return None;
4712    }
4713    let extent = maximum - minimum;
4714    (extent.is_finite() && extent > 0.0).then_some(extent)
4715}
4716
4717fn premultiplied_wgpu_color(color: Color) -> wgpu::Color {
4718    let [red, green, blue, alpha] = color.to_array();
4719    wgpu::Color {
4720        r: f64::from(red * alpha),
4721        g: f64::from(green * alpha),
4722        b: f64::from(blue * alpha),
4723        a: f64::from(alpha),
4724    }
4725}
4726
4727fn create_scalar_field_texture(
4728    device: &wgpu::Device,
4729    field: &ScalarField,
4730) -> Result<wgpu::Texture, ScalarFieldTextureError> {
4731    let extent = scalar_field_extent(field)?;
4732    let limits = device.limits();
4733    if extent.width > limits.max_texture_dimension_2d
4734        || extent.height > limits.max_texture_dimension_2d
4735    {
4736        return Err(ScalarFieldTextureError::DimensionsTooLarge);
4737    }
4738    Ok(device.create_texture(&wgpu::TextureDescriptor {
4739        label: Some("sim-engine scalar field texture"),
4740        size: extent,
4741        mip_level_count: 1,
4742        sample_count: 1,
4743        dimension: wgpu::TextureDimension::D2,
4744        format: wgpu::TextureFormat::R32Float,
4745        usage: wgpu::TextureUsages::TEXTURE_BINDING
4746            | wgpu::TextureUsages::COPY_DST
4747            | wgpu::TextureUsages::COPY_SRC,
4748        view_formats: &[],
4749    }))
4750}
4751
4752fn upload_scalar_field_texture(
4753    queue: &wgpu::Queue,
4754    texture: &wgpu::Texture,
4755    field: &ScalarField,
4756) -> Result<(), ScalarFieldTextureError> {
4757    let extent = scalar_field_extent(field)?;
4758    queue.write_texture(
4759        wgpu::TexelCopyTextureInfo {
4760            texture,
4761            mip_level: 0,
4762            origin: wgpu::Origin3d::ZERO,
4763            aspect: wgpu::TextureAspect::All,
4764        },
4765        bytemuck::cast_slice(field.values()),
4766        wgpu::TexelCopyBufferLayout {
4767            offset: 0,
4768            bytes_per_row: Some(extent.width * std::mem::size_of::<f32>() as u32),
4769            rows_per_image: Some(extent.height),
4770        },
4771        extent,
4772    );
4773    Ok(())
4774}
4775
4776fn upload_scalar_field_texture_region(
4777    queue: &wgpu::Queue,
4778    texture: &wgpu::Texture,
4779    x: usize,
4780    y: usize,
4781    width: usize,
4782    height: usize,
4783    values: &[f32],
4784) -> Result<(), ScalarFieldTextureError> {
4785    let width = u32::try_from(width).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
4786    let height = u32::try_from(height).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
4787    let x = u32::try_from(x).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
4788    let y = u32::try_from(y).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
4789    let bytes_per_row = width
4790        .checked_mul(std::mem::size_of::<f32>() as u32)
4791        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
4792    queue.write_texture(
4793        wgpu::TexelCopyTextureInfo {
4794            texture,
4795            mip_level: 0,
4796            origin: wgpu::Origin3d { x, y, z: 0 },
4797            aspect: wgpu::TextureAspect::All,
4798        },
4799        bytemuck::cast_slice(values),
4800        wgpu::TexelCopyBufferLayout {
4801            offset: 0,
4802            bytes_per_row: Some(bytes_per_row),
4803            rows_per_image: Some(height),
4804        },
4805        wgpu::Extent3d {
4806            width,
4807            height,
4808            depth_or_array_layers: 1,
4809        },
4810    );
4811    Ok(())
4812}
4813
4814fn create_scalar_field_texture_resources(
4815    device: &wgpu::Device,
4816    queue: &wgpu::Queue,
4817    renderer_identity: Arc<()>,
4818    field: ScalarField,
4819) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
4820    let texture = create_scalar_field_texture(device, &field)?;
4821    upload_scalar_field_texture(queue, &texture, &field)?;
4822    Ok(ScalarFieldTexture {
4823        renderer_identity,
4824        texture,
4825        field,
4826    })
4827}
4828
4829fn create_cached_color_map(
4830    device: &wgpu::Device,
4831    queue: &wgpu::Queue,
4832    color_map: &ColorMap,
4833) -> CachedColorMap {
4834    const COLOR_MAP_LUT_SIZE: u32 = 256;
4835    let texture = device.create_texture(&wgpu::TextureDescriptor {
4836        label: Some("sim-engine color map texture"),
4837        size: wgpu::Extent3d {
4838            width: COLOR_MAP_LUT_SIZE,
4839            height: 1,
4840            depth_or_array_layers: 1,
4841        },
4842        mip_level_count: 1,
4843        sample_count: 1,
4844        dimension: wgpu::TextureDimension::D2,
4845        format: wgpu::TextureFormat::Rgba8Unorm,
4846        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4847        view_formats: &[],
4848    });
4849    let mut bytes = Vec::with_capacity(COLOR_MAP_LUT_SIZE as usize * 4);
4850    for index in 0..COLOR_MAP_LUT_SIZE {
4851        let color = color_map.sample_normalized(index as f32 / (COLOR_MAP_LUT_SIZE - 1) as f32);
4852        bytes.extend(
4853            color
4854                .to_array()
4855                .map(|channel| (channel * 255.0).round() as u8),
4856        );
4857    }
4858    queue.write_texture(
4859        wgpu::TexelCopyTextureInfo {
4860            texture: &texture,
4861            mip_level: 0,
4862            origin: wgpu::Origin3d::ZERO,
4863            aspect: wgpu::TextureAspect::All,
4864        },
4865        &bytes,
4866        wgpu::TexelCopyBufferLayout {
4867            offset: 0,
4868            bytes_per_row: Some(1024),
4869            rows_per_image: Some(1),
4870        },
4871        wgpu::Extent3d {
4872            width: COLOR_MAP_LUT_SIZE,
4873            height: 1,
4874            depth_or_array_layers: 1,
4875        },
4876    );
4877    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4878    CachedColorMap {
4879        source: color_map.clone(),
4880        _texture: texture,
4881        view,
4882    }
4883}
4884
4885fn create_particle_unit_buffer(device: &wgpu::Device, queue: &wgpu::Queue) -> wgpu::Buffer {
4886    let buffer = device.create_buffer(&wgpu::BufferDescriptor {
4887        label: Some("sim-engine particle unit quad buffer"),
4888        size: (6 * std::mem::size_of::<ParticleUnitVertex>()) as wgpu::BufferAddress,
4889        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
4890        mapped_at_creation: false,
4891    });
4892    let unit_quad = [
4893        ParticleUnitVertex {
4894            direction: [-1.0, -1.0],
4895        },
4896        ParticleUnitVertex {
4897            direction: [1.0, -1.0],
4898        },
4899        ParticleUnitVertex {
4900            direction: [1.0, 1.0],
4901        },
4902        ParticleUnitVertex {
4903            direction: [-1.0, -1.0],
4904        },
4905        ParticleUnitVertex {
4906            direction: [1.0, 1.0],
4907        },
4908        ParticleUnitVertex {
4909            direction: [-1.0, 1.0],
4910        },
4911    ];
4912    queue.write_buffer(&buffer, 0, bytemuck::cast_slice(&unit_quad));
4913    buffer
4914}
4915
4916fn create_particle_instance_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
4917    device.create_buffer(&wgpu::BufferDescriptor {
4918        label: Some("sim-engine particle instance buffer"),
4919        size: (capacity.max(1) * std::mem::size_of::<ParticleGpu>()) as wgpu::BufferAddress,
4920        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
4921        mapped_at_creation: false,
4922    })
4923}
4924
4925mod config;
4926mod mesh3d;
4927mod tessellation;
4928mod visualization;
4929use config::{
4930    MultisampleTarget, create_multisample_target, logical_to_physical_screen,
4931    physical_to_logical_screen, validate_scale_factor,
4932};
4933pub use config::{RendererPresentMode, RendererSurfacePresentMode, WgpuRendererOptions};
4934use mesh3d::Mesh3dRenderer;
4935pub use mesh3d::{
4936    Mesh3dInstance, Mesh3dRenderError, Mesh3dRenderReport, Mesh3dResourceError, Object3dId,
4937    RenderTarget3d, RetainedMesh3d, Scene3d, Scene3dError, Scene3dRestoreReport,
4938};
4939use tessellation::{screen_clip_to_scissor, tessellate_scene};
4940use visualization::{CachedColorMap, CompositionPipelines, create_composition_pipeline};
4941pub use visualization::{LayeredVisualizationError, LayeredVisualizationOptions};
4942
4943#[cfg(test)]
4944use tessellation::world_vertex;
4945
4946#[cfg(test)]
4947mod tests;