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, Mutex},
7    time::{Duration, Instant},
8};
9
10use crate::{
11    Camera2d, Circle, Color, ColorMap, DrawCommand, Fill, Line, LogicalScreenPosition,
12    LogicalViewport, LogicalViewportRegion, ParticleInstance2d, PhysicalPerLogical,
13    PhysicalScreenPosition, Polyline, PrimitiveCommandCounts, Rect, ScalarField, Scene,
14    SceneBudgetResource, ScreenClipRect, ScreenScene, Shadow, ShapeStyle, Stroke, Vec2,
15    scene::{CIRCLE_SEGMENTS, CORNER_SEGMENTS, ROUND_CAP_SEGMENTS, TESSELLATED_VERTEX_BYTES},
16    screen::screen_camera,
17};
18use config::select_surface_present_mode;
19
20const INITIAL_VERTEX_CAPACITY: usize = 4096;
21const PREFERRED_SAMPLE_COUNT: u32 = 4;
22const COLOR_MAP_LUT_SIZE: u32 = 256;
23// Stay inside the WGSL division accuracy domain and reject denormal geometric
24// operands. This deliberately narrow transform envelope is shared by every GPU path.
25const MAX_PORTABLE_SHADER_VALUE: f32 = f32::from_bits((247_u32) << 23); // 2^120
26
27fn is_portable_shader_source(value: f32) -> bool {
28    value.is_finite()
29        && value.abs() <= MAX_PORTABLE_SHADER_VALUE
30        && (value == 0.0 || value.abs() >= f32::MIN_POSITIVE)
31}
32
33#[repr(C)]
34#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
35struct Vertex {
36    world_position: [f32; 2],
37    depth: f32,
38    world_offset: [f32; 2],
39    screen_offset: [f32; 2],
40    previous_direction: [f32; 2],
41    next_direction: [f32; 2],
42    normal_distance: f32,
43    tangent_distance: f32,
44    miter_limit: f32,
45    stroke_role: f32,
46    stroke_parameter: f32,
47    color: [f32; 4],
48}
49
50const _: () = assert!(std::mem::size_of::<Vertex>() == TESSELLATED_VERTEX_BYTES);
51
52#[repr(C)]
53#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
54struct DynamicGpu {
55    world_position: [f32; 2],
56    depth: f32,
57    color: [f32; 4],
58}
59
60#[repr(C)]
61#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
62struct CameraUniform {
63    camera_center: [f32; 4],
64    world_to_screen_x: [f32; 4],
65    world_to_screen_y: [f32; 4],
66    screen_to_clip: [f32; 4],
67}
68
69#[repr(C)]
70#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
71struct HeatmapUniform {
72    value_range: [f32; 4],
73    dimensions: [u32; 4],
74    destination: [f32; 4],
75}
76
77impl HeatmapUniform {
78    fn new(
79        minimum: f32,
80        value_extent: f32,
81        width: usize,
82        height: usize,
83        sampling: ScalarFieldSampling,
84    ) -> Self {
85        Self {
86            value_range: [minimum, value_extent, 0.0, 0.0],
87            dimensions: [width as u32, height as u32, sampling.shader_value(), 0],
88            destination: [1.0, 1.0, 0.0, 0.0],
89        }
90    }
91
92    fn in_region(mut self, region: LogicalViewportRegion, target: LogicalViewport) -> Option<Self> {
93        let destination = CompositeUniform::in_region(1.0, region, target)?.destination;
94        self.destination = destination;
95        Some(self)
96    }
97}
98
99#[repr(C)]
100#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
101struct CompositeUniform {
102    opacity: [f32; 4],
103    destination: [f32; 4],
104}
105
106impl CompositeUniform {
107    const fn full_surface(opacity: f32) -> Self {
108        Self {
109            opacity: [opacity, 0.0, 0.0, 0.0],
110            destination: [1.0, 1.0, 0.0, 0.0],
111        }
112    }
113
114    fn in_region(
115        opacity: f32,
116        region: LogicalViewportRegion,
117        target: LogicalViewport,
118    ) -> Option<Self> {
119        let origin = region.origin().to_vec2();
120        let viewport = region.viewport();
121        let scale_x = viewport.width() / target.width();
122        let scale_y = viewport.height() / target.height();
123        let offset_x = (origin.x.mul_add(2.0, viewport.width())) / target.width() - 1.0;
124        let offset_y = 1.0 - (origin.y.mul_add(2.0, viewport.height())) / target.height();
125        [scale_x, scale_y, offset_x, offset_y]
126            .into_iter()
127            .all(f32::is_finite)
128            .then_some(Self {
129                opacity: [opacity, 0.0, 0.0, 0.0],
130                destination: [scale_x, scale_y, offset_x, offset_y],
131            })
132    }
133}
134
135/// Scalar-field sampling mode used by heatmap rendering.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
137pub enum ScalarFieldSampling {
138    /// Select one exact source texel for each output fragment.
139    #[default]
140    Nearest,
141    /// Bilinearly interpolate neighboring source texels in shader math.
142    Linear,
143}
144
145impl ScalarFieldSampling {
146    fn shader_value(self) -> u32 {
147        match self {
148            Self::Nearest => 0,
149            Self::Linear => 1,
150        }
151    }
152}
153
154/// How a render target is combined with the presentation surface.
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
156pub enum BlendMode {
157    /// Standard source-alpha compositing.
158    #[default]
159    Alpha,
160    /// Adds source light to the existing destination, useful for glow and trails.
161    Additive,
162    /// Replaces destination pixels with the source target.
163    Replace,
164}
165
166/// How a target-rendering pass initializes its destination pixels.
167#[derive(Debug, Clone, Copy, PartialEq)]
168pub enum RenderTargetLoad {
169    /// Preserve existing target pixels and blend new geometry over them.
170    Load,
171    /// Clear the target to normalized finite straight-linear RGBA before drawing.
172    Clear(Color),
173}
174
175#[derive(Debug, Clone, Copy)]
176struct GeometryExtents {
177    world_min: Vec2,
178    world_max: Vec2,
179    world_offset_min: Vec2,
180    world_offset_max: Vec2,
181    depth_min: f32,
182    depth_max: f32,
183    direction_min: Vec2,
184    direction_max: Vec2,
185    screen_offset_max_abs: Vec2,
186    normal_distance_max_abs: f32,
187    tangent_distance_max_abs: f32,
188    miter_limit_max: f32,
189    vertex_count: usize,
190    empty: bool,
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194struct ScissorRect {
195    x: u32,
196    y: u32,
197    width: u32,
198    height: u32,
199}
200
201#[derive(Debug, Clone, Copy)]
202struct ParticleDrawPreparation {
203    camera_uniform: CameraUniform,
204    visible_count: usize,
205    statistics: ParticleStatistics,
206}
207
208#[derive(Debug, Clone, PartialEq)]
209struct PreparedDrawBatch {
210    vertex_range: Range<u32>,
211    screen_clip: Option<ScreenClipRect>,
212}
213
214/// Outcome of converting accepted scene commands into GPU vertices.
215///
216/// A dropped command had finite source fields but produced no finite triangle
217/// vertices, usually because arithmetic overflowed while expanding geometry.
218/// Hosts can surface this separately from presentation success.
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
220pub struct TessellationStats {
221    command_count: usize,
222    rendered_command_count: usize,
223    dropped_command_count: usize,
224    command_counts: PrimitiveCommandCounts,
225    rendered_counts: PrimitiveCommandCounts,
226    dropped_counts: PrimitiveCommandCounts,
227    vertex_count: usize,
228    draw_batch_count: usize,
229    upload_bytes: usize,
230}
231
232impl TessellationStats {
233    /// Returns accepted source commands examined by the tessellator.
234    pub fn command_count(self) -> usize {
235        self.command_count
236    }
237
238    /// Returns source commands that emitted finite triangle vertices.
239    pub fn rendered_command_count(self) -> usize {
240        self.rendered_command_count
241    }
242
243    /// Returns source commands discarded because tessellation emitted no valid geometry.
244    pub fn dropped_command_count(self) -> usize {
245        self.dropped_command_count
246    }
247
248    /// Returns accepted commands examined, grouped by primitive category.
249    pub const fn command_counts(self) -> PrimitiveCommandCounts {
250        self.command_counts
251    }
252
253    /// Returns commands that emitted geometry, grouped by primitive category.
254    pub const fn rendered_counts(self) -> PrimitiveCommandCounts {
255        self.rendered_counts
256    }
257
258    /// Returns commands that emitted no geometry, grouped by primitive category.
259    pub const fn dropped_counts(self) -> PrimitiveCommandCounts {
260        self.dropped_counts
261    }
262
263    /// Returns finite triangle-list vertices generated for this scene.
264    pub fn vertex_count(self) -> usize {
265        self.vertex_count
266    }
267
268    /// Returns draw batches generated after compatible adjacent commands merge.
269    pub fn draw_batch_count(self) -> usize {
270        self.draw_batch_count
271    }
272
273    /// Returns bytes required to upload the generated vertices.
274    pub fn upload_bytes(self) -> usize {
275        self.upload_bytes
276    }
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280enum TessellationError {
281    AllocationFailed {
282        requested_bytes: usize,
283    },
284    CapacityTooLarge,
285    BudgetExceeded {
286        resource: SceneBudgetResource,
287        limit: usize,
288        actual: usize,
289    },
290}
291
292impl Vertex {
293    const ATTRIBUTES: [wgpu::VertexAttribute; 12] = wgpu::vertex_attr_array![
294        0 => Float32x2,
295        1 => Float32,
296        2 => Float32x2,
297        3 => Float32x2,
298        4 => Float32x2,
299        5 => Float32x2,
300        6 => Float32,
301        7 => Float32,
302        8 => Float32,
303        9 => Float32,
304        10 => Float32,
305        11 => Float32x4
306    ];
307
308    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
309        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
310        step_mode: wgpu::VertexStepMode::Vertex,
311        attributes: &Self::ATTRIBUTES,
312    };
313
314    fn is_finite(self) -> bool {
315        self.world_position.iter().all(|value| value.is_finite())
316            && self.depth.is_finite()
317            && self.world_offset.iter().all(|value| value.is_finite())
318            && self.screen_offset.iter().all(|value| value.is_finite())
319            && self
320                .previous_direction
321                .iter()
322                .all(|value| value.is_finite())
323            && self.next_direction.iter().all(|value| value.is_finite())
324            && self.normal_distance.is_finite()
325            && self.tangent_distance.is_finite()
326            && self.miter_limit.is_finite()
327            && self.stroke_role.is_finite()
328            && self.stroke_parameter.is_finite()
329            && self.color.iter().all(|value| value.is_finite())
330    }
331}
332
333impl DynamicGpu {
334    const ATTRIBUTES: [wgpu::VertexAttribute; 3] =
335        wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32, 2 => Float32x4];
336
337    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
338        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
339        step_mode: wgpu::VertexStepMode::Vertex,
340        attributes: &Self::ATTRIBUTES,
341    };
342}
343
344#[repr(C)]
345#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
346struct ParticleUnitVertex {
347    direction: [f32; 2],
348}
349
350impl ParticleUnitVertex {
351    const ATTRIBUTES: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![0 => Float32x2];
352
353    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
354        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
355        step_mode: wgpu::VertexStepMode::Vertex,
356        attributes: &Self::ATTRIBUTES,
357    };
358}
359
360#[repr(C)]
361#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
362struct ParticleGpu {
363    world_position: [f32; 2],
364    depth: f32,
365    radius: f32,
366    color: [f32; 4],
367}
368
369impl ParticleGpu {
370    const ATTRIBUTES: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![
371        1 => Float32x2,
372        2 => Float32,
373        3 => Float32,
374        4 => Float32x4
375    ];
376
377    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
378        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
379        step_mode: wgpu::VertexStepMode::Instance,
380        attributes: &Self::ATTRIBUTES,
381    };
382
383    #[cfg(test)]
384    fn screen_position(self, camera: CameraUniform) -> Vec2 {
385        let relative_x = self.world_position[0] - camera.camera_center[0];
386        let relative_y = self.world_position[1] - camera.camera_center[1];
387        Vec2::new(
388            camera.world_to_screen_x[0] * relative_x
389                + camera.world_to_screen_x[1] * relative_y
390                + camera.world_to_screen_x[2] * self.depth
391                + camera.world_to_screen_x[3],
392            camera.world_to_screen_y[0] * relative_x
393                + camera.world_to_screen_y[1] * relative_y
394                + camera.world_to_screen_y[2] * self.depth
395                + camera.world_to_screen_y[3],
396        )
397    }
398
399    fn is_safe_for(self, camera: CameraUniform, viewport: LogicalViewport) -> bool {
400        self.validated_viewport_intersection(camera, viewport)
401            .is_some()
402    }
403
404    fn transform_sources_are_portable(self) -> bool {
405        self.world_position
406            .into_iter()
407            .chain([self.depth, self.radius])
408            .all(is_portable_shader_source)
409    }
410
411    fn projected_screen_bounds(self, camera: CameraUniform) -> Option<((f64, f64), (f64, f64))> {
412        let center = self.projected_screen_center_bounds(camera)?;
413        let radius = f64::from(self.radius);
414        Some((
415            shader_interval_sum_range([center.0, (-radius, radius)])?,
416            shader_interval_sum_range([center.1, (-radius, radius)])?,
417        ))
418    }
419
420    fn projected_screen_center_bounds(
421        self,
422        camera: CameraUniform,
423    ) -> Option<((f64, f64), (f64, f64))> {
424        let relative_x = shader_relative_component_bounds(
425            self.world_position[0],
426            self.world_position[0],
427            camera.camera_center[0],
428            0.0,
429            0.0,
430        )?;
431        let relative_y = shader_relative_component_bounds(
432            self.world_position[1],
433            self.world_position[1],
434            camera.camera_center[1],
435            0.0,
436            0.0,
437        )?;
438        let relative_minimum = [relative_x.0, relative_y.0];
439        let relative_maximum = [relative_x.1, relative_y.1];
440        Some((
441            shader_world_dot_range(
442                camera.world_to_screen_x,
443                relative_minimum,
444                relative_maximum,
445                self.depth,
446                self.depth,
447            )?,
448            shader_world_dot_range(
449                camera.world_to_screen_y,
450                relative_minimum,
451                relative_maximum,
452                self.depth,
453                self.depth,
454            )?,
455        ))
456    }
457
458    fn screen_bounds_intersect_viewport(
459        bounds: ((f64, f64), (f64, f64)),
460        viewport: LogicalViewport,
461    ) -> bool {
462        bounds.0.1 >= 0.0
463            && bounds.0.0 <= f64::from(viewport.width())
464            && bounds.1.1 >= 0.0
465            && bounds.1.0 <= f64::from(viewport.height())
466    }
467
468    fn validated_viewport_intersection(
469        self,
470        camera: CameraUniform,
471        viewport: LogicalViewport,
472    ) -> Option<bool> {
473        if !self.transform_sources_are_portable() || !camera.sources_are_portable() {
474            return None;
475        }
476        let center = self.projected_screen_center_bounds(camera)?;
477        if !self.clip_expansion_is_stable(center, camera) {
478            return None;
479        }
480        let radius = f64::from(self.radius);
481        let width = f64::from(viewport.width());
482        let height = f64::from(viewport.height());
483        let wholly_outside = center.0.1 + radius < 0.0
484            || center.0.0 - radius > width
485            || center.1.1 + radius < 0.0
486            || center.1.0 - radius > height;
487        if wholly_outside {
488            return Some(false);
489        }
490        // Every permitted dot/FMA association must leave a positive-area
491        // portion of the quad inside the viewport. If visibility itself can
492        // change between legal shader lowerings, fail closed before upload.
493        let always_intersects = center.0.0 + radius > 0.0
494            && center.0.1 - radius < width
495            && center.1.0 + radius > 0.0
496            && center.1.1 - radius < height;
497        always_intersects.then_some(true)
498    }
499
500    fn clip_expansion_is_stable(
501        self,
502        center: ((f64, f64), (f64, f64)),
503        camera: CameraUniform,
504    ) -> bool {
505        (0..2).all(|axis| {
506            let center_clip = rounded_f32_product_range(
507                center_axis(center, axis),
508                (
509                    f64::from(camera.screen_to_clip[axis]),
510                    f64::from(camera.screen_to_clip[axis]),
511                ),
512            )
513            .and_then(|scaled| {
514                rounded_f32_add_range(
515                    scaled,
516                    (
517                        f64::from(camera.screen_to_clip[axis + 2]),
518                        f64::from(camera.screen_to_clip[axis + 2]),
519                    ),
520                    false,
521                )
522            });
523            let extent = rounded_f32_product_range(
524                (f64::from(self.radius), f64::from(self.radius)),
525                (
526                    f64::from(camera.screen_to_clip[axis].abs()),
527                    f64::from(camera.screen_to_clip[axis].abs()),
528                ),
529            );
530            let (Some(center_clip), Some(extent)) = (center_clip, extent) else {
531                return false;
532            };
533            if extent.0 < f64::from(f32::MIN_POSITIVE) {
534                return false;
535            }
536            let Some(negative) = rounded_f32_add_range(center_clip, extent, true) else {
537                return false;
538            };
539            let Some(positive) = rounded_f32_add_range(center_clip, extent, false) else {
540                return false;
541            };
542            positive.0 - negative.1 >= f64::from(f32::MIN_POSITIVE)
543        })
544    }
545
546    fn intersects_viewport(self, camera: CameraUniform, viewport: LogicalViewport) -> bool {
547        // Validation precedes production culling. If this helper is called on
548        // an invalid instance, keep it conservatively instead of silently
549        // dropping geometry based on one CPU association of the shader dot.
550        self.projected_screen_bounds(camera)
551            .is_none_or(|bounds| Self::screen_bounds_intersect_viewport(bounds, viewport))
552    }
553}
554
555fn center_axis(center: ((f64, f64), (f64, f64)), axis: usize) -> (f64, f64) {
556    if axis == 0 { center.0 } else { center.1 }
557}
558
559impl CameraUniform {
560    fn new(camera: Camera2d, viewport: LogicalViewport) -> Option<Self> {
561        Self::new_in_region(camera, viewport, Vec2::ZERO, viewport)
562    }
563
564    fn new_in_region(
565        camera: Camera2d,
566        viewport: LogicalViewport,
567        target_origin: Vec2,
568        target_viewport: LogicalViewport,
569    ) -> Option<Self> {
570        let projection_cosine = camera.projection().tilt().cos();
571        let rotation_cosine = camera.rotation().cos();
572        let rotation_sine = camera.rotation().sin();
573        let zoom = camera.zoom();
574        let center = camera.center();
575        let projection_sine = camera.projection().tilt().sin();
576        let depth_scale = camera.projection().depth_scale();
577
578        let horizontal_x = zoom * rotation_cosine;
579        let horizontal_y = -zoom * rotation_sine * projection_cosine;
580        let vertical_x = -zoom * rotation_sine;
581        let vertical_y = -zoom * rotation_cosine * projection_cosine;
582        let horizontal_depth =
583            zoom * depth_scale * projection_sine * (rotation_cosine * 0.5 - rotation_sine);
584        let vertical_depth =
585            -zoom * depth_scale * projection_sine * (rotation_sine * 0.5 + rotation_cosine);
586
587        let uniform = Self {
588            camera_center: [center.x, center.y, 0.0, 0.0],
589            world_to_screen_x: [
590                horizontal_x,
591                horizontal_y,
592                horizontal_depth,
593                target_origin.x + viewport.width() * 0.5,
594            ],
595            world_to_screen_y: [
596                vertical_x,
597                vertical_y,
598                vertical_depth,
599                target_origin.y + viewport.height() * 0.5,
600            ],
601            screen_to_clip: [
602                2.0 / target_viewport.width(),
603                -2.0 / target_viewport.height(),
604                -1.0,
605                1.0,
606            ],
607        };
608        (uniform.is_finite() && uniform.sources_are_portable()).then_some(uniform)
609    }
610
611    fn sources_are_portable(self) -> bool {
612        self.camera_center
613            .into_iter()
614            .chain(self.world_to_screen_x)
615            .chain(self.world_to_screen_y)
616            .chain(self.screen_to_clip)
617            .all(is_portable_shader_source)
618    }
619
620    fn is_finite(self) -> bool {
621        self.camera_center
622            .iter()
623            .chain(self.world_to_screen_x.iter())
624            .chain(self.world_to_screen_y.iter())
625            .chain(self.screen_to_clip.iter())
626            .all(|value| value.is_finite())
627    }
628
629    fn world_to_screen(self, world: Vec2, depth: f32) -> Vec2 {
630        let relative = world - Vec2::new(self.camera_center[0], self.camera_center[1]);
631        Vec2::new(
632            self.world_to_screen_x[0] * relative.x
633                + self.world_to_screen_x[1] * relative.y
634                + self.world_to_screen_x[2] * depth
635                + self.world_to_screen_x[3],
636            self.world_to_screen_y[0] * relative.x
637                + self.world_to_screen_y[1] * relative.y
638                + self.world_to_screen_y[2] * depth
639                + self.world_to_screen_y[3],
640        )
641    }
642
643    #[cfg(test)]
644    fn direction_to_screen(self, direction: Vec2) -> Vec2 {
645        Vec2::new(
646            self.world_to_screen_x[0] * direction.x + self.world_to_screen_x[1] * direction.y,
647            self.world_to_screen_y[0] * direction.x + self.world_to_screen_y[1] * direction.y,
648        )
649    }
650}
651
652impl GeometryExtents {
653    fn empty(is_empty: bool) -> Self {
654        Self {
655            world_min: Vec2::splat(f32::INFINITY),
656            world_max: Vec2::splat(f32::NEG_INFINITY),
657            world_offset_min: Vec2::splat(f32::INFINITY),
658            world_offset_max: Vec2::splat(f32::NEG_INFINITY),
659            depth_min: f32::INFINITY,
660            depth_max: f32::NEG_INFINITY,
661            direction_min: Vec2::splat(f32::INFINITY),
662            direction_max: Vec2::splat(f32::NEG_INFINITY),
663            screen_offset_max_abs: Vec2::ZERO,
664            normal_distance_max_abs: 0.0,
665            tangent_distance_max_abs: 0.0,
666            miter_limit_max: 1.0,
667            vertex_count: 0,
668            empty: is_empty,
669        }
670    }
671
672    fn include(&mut self, vertex: Vertex) {
673        self.vertex_count += 1;
674        let world = Vec2::new(vertex.world_position[0], vertex.world_position[1]);
675        self.world_min.x = self.world_min.x.min(world.x);
676        self.world_min.y = self.world_min.y.min(world.y);
677        self.world_max.x = self.world_max.x.max(world.x);
678        self.world_max.y = self.world_max.y.max(world.y);
679        let world_offset = Vec2::new(vertex.world_offset[0], vertex.world_offset[1]);
680        self.world_offset_min.x = self.world_offset_min.x.min(world_offset.x);
681        self.world_offset_min.y = self.world_offset_min.y.min(world_offset.y);
682        self.world_offset_max.x = self.world_offset_max.x.max(world_offset.x);
683        self.world_offset_max.y = self.world_offset_max.y.max(world_offset.y);
684        self.depth_min = self.depth_min.min(vertex.depth);
685        self.depth_max = self.depth_max.max(vertex.depth);
686
687        for direction in [vertex.previous_direction, vertex.next_direction] {
688            self.direction_min.x = self.direction_min.x.min(direction[0]);
689            self.direction_min.y = self.direction_min.y.min(direction[1]);
690            self.direction_max.x = self.direction_max.x.max(direction[0]);
691            self.direction_max.y = self.direction_max.y.max(direction[1]);
692        }
693
694        self.screen_offset_max_abs.x = self
695            .screen_offset_max_abs
696            .x
697            .max(vertex.screen_offset[0].abs());
698        self.screen_offset_max_abs.y = self
699            .screen_offset_max_abs
700            .y
701            .max(vertex.screen_offset[1].abs());
702        self.normal_distance_max_abs = self
703            .normal_distance_max_abs
704            .max(vertex.normal_distance.abs());
705        self.tangent_distance_max_abs = self
706            .tangent_distance_max_abs
707            .max(vertex.tangent_distance.abs());
708        self.miter_limit_max = self.miter_limit_max.max(vertex.miter_limit);
709    }
710
711    fn include_dynamic(&mut self, vertex: DynamicGpu) {
712        self.vertex_count += 1;
713        let world = Vec2::new(vertex.world_position[0], vertex.world_position[1]);
714        self.world_min.x = self.world_min.x.min(world.x);
715        self.world_min.y = self.world_min.y.min(world.y);
716        self.world_max.x = self.world_max.x.max(world.x);
717        self.world_max.y = self.world_max.y.max(world.y);
718        self.world_offset_min = Vec2::ZERO;
719        self.world_offset_max = Vec2::ZERO;
720        self.depth_min = self.depth_min.min(vertex.depth);
721        self.depth_max = self.depth_max.max(vertex.depth);
722        self.direction_min = Vec2::ZERO;
723        self.direction_max = Vec2::ZERO;
724    }
725
726    fn from_dynamic_vertices(vertices: &[DynamicGpu]) -> Self {
727        let mut extents = Self::empty(vertices.is_empty());
728        for vertex in vertices {
729            extents.include_dynamic(*vertex);
730        }
731        extents
732    }
733
734    fn from_vertices(vertices: &[Vertex]) -> Self {
735        let mut extents = Self::empty(vertices.is_empty());
736        for vertex in vertices {
737            extents.include(*vertex);
738        }
739
740        extents
741    }
742
743    fn is_safe_for(self, uniform: CameraUniform) -> bool {
744        if self.empty {
745            return true;
746        }
747        let center = Vec2::new(uniform.camera_center[0], uniform.camera_center[1]);
748        // Match the vertex shader's split-anchor operation order. Generated
749        // local offsets are projected separately so they cannot disappear
750        // when their world anchor is much larger than the local geometry.
751        let Some(relative_horizontal) = shader_relative_component_bounds(
752            self.world_min.x,
753            self.world_max.x,
754            center.x,
755            0.0,
756            0.0,
757        ) else {
758            return false;
759        };
760        let Some(relative_vertical) = shader_relative_component_bounds(
761            self.world_min.y,
762            self.world_max.y,
763            center.y,
764            0.0,
765            0.0,
766        ) else {
767            return false;
768        };
769        let relative_minimum = [relative_horizontal.0, relative_vertical.0];
770        let relative_maximum = [relative_horizontal.1, relative_vertical.1];
771        let Some(projected_world_horizontal) = shader_world_dot_range(
772            uniform.world_to_screen_x,
773            relative_minimum,
774            relative_maximum,
775            self.depth_min,
776            self.depth_max,
777        ) else {
778            return false;
779        };
780        let Some(projected_world_vertical) = shader_world_dot_range(
781            uniform.world_to_screen_y,
782            relative_minimum,
783            relative_maximum,
784            self.depth_min,
785            self.depth_max,
786        ) else {
787            return false;
788        };
789        let Some(projected_offset_horizontal) = shader_direction_dot_range(
790            uniform.world_to_screen_x,
791            self.world_offset_min,
792            self.world_offset_max,
793        ) else {
794            return false;
795        };
796        let Some(projected_offset_vertical) = shader_direction_dot_range(
797            uniform.world_to_screen_y,
798            self.world_offset_min,
799            self.world_offset_max,
800        ) else {
801            return false;
802        };
803        let Some(world_horizontal) =
804            shader_interval_sum_range([projected_world_horizontal, projected_offset_horizontal])
805        else {
806            return false;
807        };
808        let Some(world_vertical) =
809            shader_interval_sum_range([projected_world_vertical, projected_offset_vertical])
810        else {
811            return false;
812        };
813        let Some(direction_horizontal) = shader_direction_dot_range(
814            uniform.world_to_screen_x,
815            self.direction_min,
816            self.direction_max,
817        ) else {
818            return false;
819        };
820        let Some(direction_vertical) = shader_direction_dot_range(
821            uniform.world_to_screen_y,
822            self.direction_min,
823            self.direction_max,
824        ) else {
825            return false;
826        };
827        if [
828            self.screen_offset_max_abs.x,
829            self.screen_offset_max_abs.y,
830            self.normal_distance_max_abs,
831            self.tangent_distance_max_abs,
832        ]
833        .into_iter()
834        .any(is_nonzero_subnormal)
835        {
836            return false;
837        }
838        let Some(horizontal_bounds) = shader_stroke_screen_bounds(
839            world_horizontal,
840            self.screen_offset_max_abs.x,
841            self.normal_distance_max_abs,
842            self.tangent_distance_max_abs,
843            self.miter_limit_max,
844        ) else {
845            return false;
846        };
847        let Some(vertical_bounds) = shader_stroke_screen_bounds(
848            world_vertical,
849            self.screen_offset_max_abs.y,
850            self.normal_distance_max_abs,
851            self.tangent_distance_max_abs,
852            self.miter_limit_max,
853        ) else {
854            return false;
855        };
856
857        if !shader_clip_interval_is_safe(
858            horizontal_bounds.0,
859            horizontal_bounds.1,
860            uniform.screen_to_clip[0],
861            uniform.screen_to_clip[2],
862        ) || !shader_clip_interval_is_safe(
863            vertical_bounds.0,
864            vertical_bounds.1,
865            uniform.screen_to_clip[1],
866            uniform.screen_to_clip[3],
867        ) {
868            return false;
869        }
870
871        [
872            world_horizontal.0,
873            world_horizontal.1,
874            world_vertical.0,
875            world_vertical.1,
876            direction_horizontal.0,
877            direction_horizontal.1,
878            direction_vertical.0,
879            direction_vertical.1,
880            horizontal_bounds.0,
881            horizontal_bounds.1,
882            vertical_bounds.0,
883            vertical_bounds.1,
884        ]
885        .into_iter()
886        .all(|value| value.is_finite() && value.abs() <= f32::MAX as f64)
887    }
888}
889
890fn shader_stroke_screen_bounds(
891    world_screen: (f64, f64),
892    screen_offset_max_abs: f32,
893    normal_distance_max_abs: f32,
894    tangent_distance_max_abs: f32,
895    miter_limit_max: f32,
896) -> Option<(f64, f64)> {
897    // `safe_unit` and the miter path are backend-selected inverse-square-root
898    // arithmetic. A component of a mathematically unit vector is at most one;
899    // two is a deliberately loose portable bound that also contains its
900    // permitted approximation error. Propagate the shader's two additions
901    // separately so a tiny later clip scale cannot hide screen-space overflow.
902    const UNIT_COMPONENT_BOUND: f64 = 2.0;
903    let normal = f64::from(normal_distance_max_abs);
904    let tangent = f64::from(tangent_distance_max_abs);
905    let miter = normal * f64::from(miter_limit_max.max(1.0));
906    let normal_component = UNIT_COMPONENT_BOUND * normal.max(miter);
907    let tangent_component = UNIT_COMPONENT_BOUND * tangent;
908    let extrusion = shader_interval_sum_range([
909        (-normal_component, normal_component),
910        (-tangent_component, tangent_component),
911    ])?;
912    let offset = f64::from(screen_offset_max_abs);
913    shader_interval_sum_range([world_screen, extrusion, (-offset, offset)])
914}
915
916#[derive(Clone, Copy)]
917enum GeometryValidationSource<'a> {
918    Tessellated(&'a [Vertex]),
919    Dynamic(&'a [DynamicGpu]),
920}
921
922const GEOMETRY_VALIDATION_CACHE_CAPACITY: usize = 8;
923
924#[derive(Clone, Copy)]
925struct GeometryValidationCacheEntry {
926    uniform: CameraUniform,
927    safe: bool,
928}
929
930struct GeometryValidationCacheState {
931    entries: [Option<GeometryValidationCacheEntry>; GEOMETRY_VALIDATION_CACHE_CAPACITY],
932    next: usize,
933}
934
935impl Default for GeometryValidationCacheState {
936    fn default() -> Self {
937        Self {
938            entries: [None; GEOMETRY_VALIDATION_CACHE_CAPACITY],
939            next: 0,
940        }
941    }
942}
943
944#[derive(Default)]
945struct GeometryValidationCache {
946    state: Mutex<GeometryValidationCacheState>,
947}
948
949impl GeometryValidationCache {
950    fn validate(
951        &self,
952        extents: GeometryExtents,
953        source: GeometryValidationSource<'_>,
954        uniform: CameraUniform,
955    ) -> bool {
956        {
957            let state = self.state.lock().unwrap_or_else(|error| error.into_inner());
958            if let Some(entry) = state
959                .entries
960                .iter()
961                .flatten()
962                .find(|entry| entry.uniform == uniform)
963            {
964                return entry.safe;
965            }
966        }
967
968        let safe = geometry_is_safe_for(extents, source, uniform);
969        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
970        if let Some(entry) = state
971            .entries
972            .iter()
973            .flatten()
974            .find(|entry| entry.uniform == uniform)
975        {
976            return entry.safe;
977        }
978        let next = state.next;
979        state.entries[next] = Some(GeometryValidationCacheEntry { uniform, safe });
980        state.next = (next + 1) % GEOMETRY_VALIDATION_CACHE_CAPACITY;
981        safe
982    }
983
984    fn clear(&mut self) {
985        let state = self
986            .state
987            .get_mut()
988            .unwrap_or_else(|error| error.into_inner());
989        *state = GeometryValidationCacheState::default();
990    }
991}
992
993fn geometry_is_safe_for_cached(
994    cache: Option<&GeometryValidationCache>,
995    extents: GeometryExtents,
996    source: GeometryValidationSource<'_>,
997    uniform: CameraUniform,
998) -> bool {
999    cache.map_or_else(
1000        || geometry_is_safe_for(extents, source, uniform),
1001        |cache| cache.validate(extents, source, uniform),
1002    )
1003}
1004
1005fn geometry_is_safe_for(
1006    extents: GeometryExtents,
1007    source: GeometryValidationSource<'_>,
1008    uniform: CameraUniform,
1009) -> bool {
1010    geometry_sources_are_portable(source)
1011        && match source {
1012            GeometryValidationSource::Tessellated(vertices) => {
1013                geometry_vertex_centers_are_portable(source, uniform)
1014                    && tessellated_triangle_topology_is_portable(vertices, uniform)
1015                    && vertices
1016                        .iter()
1017                        .all(|vertex| logical_stroke_branches_are_stable(*vertex, uniform))
1018            }
1019            GeometryValidationSource::Dynamic(vertices) => {
1020                // The triangle proof projects every vertex itself, so do not
1021                // duplicate the same per-vertex dot envelopes first.
1022                dynamic_triangle_topology_is_portable(vertices, uniform)
1023            }
1024        }
1025        && uniform.sources_are_portable()
1026        && extents.is_safe_for(uniform)
1027}
1028
1029fn dynamic_triangle_topology_is_portable(vertices: &[DynamicGpu], uniform: CameraUniform) -> bool {
1030    if !vertices.len().is_multiple_of(3) {
1031        return false;
1032    }
1033    let minimum_normal = f64::from(f32::MIN_POSITIVE);
1034    for triangle in vertices.chunks_exact(3) {
1035        let Some(first) = dynamic_vertex_clip_ranges(triangle[0], uniform) else {
1036            return false;
1037        };
1038        let Some(second) = dynamic_vertex_clip_ranges(triangle[1], uniform) else {
1039            return false;
1040        };
1041        let Some(third) = dynamic_vertex_clip_ranges(triangle[2], uniform) else {
1042            return false;
1043        };
1044        let clip = [first, second, third];
1045        if clip_triangle_is_wholly_outside(clip) {
1046            continue;
1047        }
1048        if !clip_triangle_is_wholly_inside(clip) {
1049            // v0.2 does not yet carry conservative interval polygons through
1050            // hardware clipping. Reject partially clipped dynamic triangles
1051            // rather than permit backend-selected topology.
1052            return false;
1053        }
1054        if !clip_triangle_has_stable_signed_area(clip, minimum_normal) {
1055            return false;
1056        }
1057    }
1058    true
1059}
1060
1061fn tessellated_triangle_topology_is_portable(vertices: &[Vertex], uniform: CameraUniform) -> bool {
1062    if !vertices.len().is_multiple_of(3) {
1063        return false;
1064    }
1065    let minimum_normal = f64::from(f32::MIN_POSITIVE);
1066    for triangle in vertices.chunks_exact(3) {
1067        let has_shader_extrusion = !triangle
1068            .iter()
1069            .all(|vertex| vertex.normal_distance == 0.0 && vertex.tangent_distance == 0.0);
1070        if has_shader_extrusion {
1071            let Some(first) = logical_stroke_vertex_screen_ranges(triangle[0], uniform) else {
1072                return false;
1073            };
1074            let Some(second) = logical_stroke_vertex_screen_ranges(triangle[1], uniform) else {
1075                return false;
1076            };
1077            let Some(third) = logical_stroke_vertex_screen_ranges(triangle[2], uniform) else {
1078                return false;
1079            };
1080            if [first, second, third].iter().all(|output| output.1)
1081                && triangle_position_sources_equal(triangle)
1082            {
1083                continue;
1084            }
1085            let Some(first) = screen_ranges_to_clip(first.0, uniform) else {
1086                return false;
1087            };
1088            let Some(second) = screen_ranges_to_clip(second.0, uniform) else {
1089                return false;
1090            };
1091            let Some(third) = screen_ranges_to_clip(third.0, uniform) else {
1092                return false;
1093            };
1094            let clip = [first, second, third];
1095            if !clip_triangle_is_wholly_outside(clip)
1096                && !clip_triangle_has_stable_signed_area(clip, minimum_normal)
1097            {
1098                return false;
1099            }
1100            continue;
1101        }
1102        let Some(first) = tessellated_vertex_clip_ranges(triangle[0], uniform) else {
1103            return false;
1104        };
1105        let Some(second) = tessellated_vertex_clip_ranges(triangle[1], uniform) else {
1106            return false;
1107        };
1108        let Some(third) = tessellated_vertex_clip_ranges(triangle[2], uniform) else {
1109            return false;
1110        };
1111        let clip = [first, second, third];
1112        if clip_triangle_is_wholly_outside(clip) {
1113            continue;
1114        }
1115        if !clip_triangle_has_stable_signed_area(clip, minimum_normal) {
1116            return false;
1117        }
1118    }
1119    true
1120}
1121
1122fn clip_triangle_is_wholly_outside(clip: [[(f64, f64); 2]; 3]) -> bool {
1123    (0..2).any(|axis| {
1124        clip.iter().all(|point| point[axis].1 < -1.0)
1125            || clip.iter().all(|point| point[axis].0 > 1.0)
1126    })
1127}
1128
1129fn clip_triangle_is_wholly_inside(clip: [[(f64, f64); 2]; 3]) -> bool {
1130    clip.iter()
1131        .all(|point| point.iter().all(|axis| axis.0 >= -1.0 && axis.1 <= 1.0))
1132}
1133
1134fn clip_triangle_has_stable_signed_area(
1135    clip: [[(f64, f64); 2]; 3],
1136    minimum_magnitude: f64,
1137) -> bool {
1138    let Some(first_x) = shader_interval_difference(clip[1][0], clip[0][0]) else {
1139        return false;
1140    };
1141    let Some(first_y) = shader_interval_difference(clip[2][1], clip[0][1]) else {
1142        return false;
1143    };
1144    let Some(second_y) = shader_interval_difference(clip[1][1], clip[0][1]) else {
1145        return false;
1146    };
1147    let Some(second_x) = shader_interval_difference(clip[2][0], clip[0][0]) else {
1148        return false;
1149    };
1150    let Some(positive) = shader_interval_product(first_x, first_y) else {
1151        return false;
1152    };
1153    let Some(negative) = shader_interval_product(second_y, second_x) else {
1154        return false;
1155    };
1156    let Some(area) = shader_interval_difference(positive, negative) else {
1157        return false;
1158    };
1159    area.0 >= minimum_magnitude || area.1 <= -minimum_magnitude
1160}
1161
1162fn dynamic_vertex_clip_ranges(
1163    vertex: DynamicGpu,
1164    uniform: CameraUniform,
1165) -> Option<[(f64, f64); 2]> {
1166    let relative_x = shader_relative_component_bounds(
1167        vertex.world_position[0],
1168        vertex.world_position[0],
1169        uniform.camera_center[0],
1170        0.0,
1171        0.0,
1172    )?;
1173    let relative_y = shader_relative_component_bounds(
1174        vertex.world_position[1],
1175        vertex.world_position[1],
1176        uniform.camera_center[1],
1177        0.0,
1178        0.0,
1179    )?;
1180    let minimum = [relative_x.0, relative_y.0];
1181    let maximum = [relative_x.1, relative_y.1];
1182    let screen = [
1183        shader_world_dot_range(
1184            uniform.world_to_screen_x,
1185            minimum,
1186            maximum,
1187            vertex.depth,
1188            vertex.depth,
1189        )?,
1190        shader_world_dot_range(
1191            uniform.world_to_screen_y,
1192            minimum,
1193            maximum,
1194            vertex.depth,
1195            vertex.depth,
1196        )?,
1197    ];
1198    screen_ranges_to_clip(screen, uniform)
1199}
1200
1201fn tessellated_vertex_clip_ranges(
1202    vertex: Vertex,
1203    uniform: CameraUniform,
1204) -> Option<[(f64, f64); 2]> {
1205    screen_ranges_to_clip(tessellated_vertex_screen_ranges(vertex, uniform)?, uniform)
1206}
1207
1208fn tessellated_vertex_screen_ranges(
1209    vertex: Vertex,
1210    uniform: CameraUniform,
1211) -> Option<[(f64, f64); 2]> {
1212    let base = tessellated_vertex_base_screen_ranges(vertex, uniform)?;
1213    Some([
1214        rounded_f32_add_range(
1215            base[0],
1216            (
1217                f64::from(vertex.screen_offset[0]),
1218                f64::from(vertex.screen_offset[0]),
1219            ),
1220            false,
1221        )?,
1222        rounded_f32_add_range(
1223            base[1],
1224            (
1225                f64::from(vertex.screen_offset[1]),
1226                f64::from(vertex.screen_offset[1]),
1227            ),
1228            false,
1229        )?,
1230    ])
1231}
1232
1233fn tessellated_vertex_base_screen_ranges(
1234    vertex: Vertex,
1235    uniform: CameraUniform,
1236) -> Option<[(f64, f64); 2]> {
1237    let relative_x = shader_relative_component_bounds(
1238        vertex.world_position[0],
1239        vertex.world_position[0],
1240        uniform.camera_center[0],
1241        0.0,
1242        0.0,
1243    )?;
1244    let relative_y = shader_relative_component_bounds(
1245        vertex.world_position[1],
1246        vertex.world_position[1],
1247        uniform.camera_center[1],
1248        0.0,
1249        0.0,
1250    )?;
1251    let minimum = [relative_x.0, relative_y.0];
1252    let maximum = [relative_x.1, relative_y.1];
1253    let world_offset = Vec2::new(vertex.world_offset[0], vertex.world_offset[1]);
1254    Some([
1255        shader_interval_sum_range([
1256            shader_world_dot_range(
1257                uniform.world_to_screen_x,
1258                minimum,
1259                maximum,
1260                vertex.depth,
1261                vertex.depth,
1262            )?,
1263            shader_direction_dot_range(uniform.world_to_screen_x, world_offset, world_offset)?,
1264        ])?,
1265        shader_interval_sum_range([
1266            shader_world_dot_range(
1267                uniform.world_to_screen_y,
1268                minimum,
1269                maximum,
1270                vertex.depth,
1271                vertex.depth,
1272            )?,
1273            shader_direction_dot_range(uniform.world_to_screen_y, world_offset, world_offset)?,
1274        ])?,
1275    ])
1276}
1277
1278fn triangle_position_sources_equal(triangle: &[Vertex]) -> bool {
1279    triangle.windows(2).all(|pair| {
1280        pair[0].world_position == pair[1].world_position
1281            && pair[0].depth == pair[1].depth
1282            && pair[0].world_offset == pair[1].world_offset
1283            && pair[0].screen_offset == pair[1].screen_offset
1284    })
1285}
1286
1287fn logical_stroke_vertex_screen_ranges(
1288    vertex: Vertex,
1289    uniform: CameraUniform,
1290) -> Option<([(f64, f64); 2], bool)> {
1291    let base = tessellated_vertex_base_screen_ranges(vertex, uniform)?;
1292    let previous_source = Vec2::new(vertex.previous_direction[0], vertex.previous_direction[1]);
1293    let next_source = Vec2::new(vertex.next_direction[0], vertex.next_direction[1]);
1294    let previous_projected = [
1295        shader_direction_dot_range(uniform.world_to_screen_x, previous_source, previous_source)?,
1296        shader_direction_dot_range(uniform.world_to_screen_y, previous_source, previous_source)?,
1297    ];
1298    let next_projected = if vertex.previous_direction == vertex.next_direction {
1299        previous_projected
1300    } else {
1301        [
1302            shader_direction_dot_range(uniform.world_to_screen_x, next_source, next_source)?,
1303            shader_direction_dot_range(uniform.world_to_screen_y, next_source, next_source)?,
1304        ]
1305    };
1306    let previous_tangent = stroke_safe_unit_range(previous_projected)?;
1307    let next_tangent = if vertex.previous_direction == vertex.next_direction {
1308        previous_tangent
1309    } else {
1310        stroke_safe_unit_range(next_projected)?
1311    };
1312    let previous_normal = [range_negate(previous_tangent[1]), previous_tangent[0]];
1313    let next_normal = [range_negate(next_tangent[1]), next_tangent[0]];
1314    let turn = if vertex.previous_direction == vertex.next_direction {
1315        (0.0, 0.0)
1316    } else {
1317        rounded_f32_add_range(
1318            rounded_f32_product_range(previous_tangent[0], next_tangent[1])?,
1319            rounded_f32_product_range(previous_tangent[1], next_tangent[0])?,
1320            true,
1321        )?
1322    };
1323    let turn_sign = if turn.0 > 0.0 {
1324        1.0
1325    } else if turn.1 < 0.0 {
1326        -1.0
1327    } else if vertex.previous_direction == vertex.next_direction {
1328        0.0
1329    } else {
1330        return None;
1331    };
1332    let combined_normal = [
1333        rounded_f32_add_range(previous_normal[0], next_normal[0], false)?,
1334        rounded_f32_add_range(previous_normal[1], next_normal[1], false)?,
1335    ];
1336    let miter = stroke_safe_unit_range(combined_normal);
1337    let miter_state = miter.and_then(|miter| {
1338        let denominator = range_dot(miter, next_normal)?;
1339        if denominator.0 <= 0.001 && denominator.1 >= -0.001 {
1340            return None;
1341        }
1342        let reciprocal = rounded_f32_division_range((1.0, 1.0), denominator)?;
1343        let multiple = range_abs(reciprocal);
1344        let limit = f64::from(vertex.miter_limit);
1345        let within_limit = if multiple.1 <= limit {
1346            true
1347        } else if multiple.0 > limit {
1348            false
1349        } else {
1350            return None;
1351        };
1352        let scalar = rounded_f32_product_range(
1353            reciprocal,
1354            (
1355                f64::from(vertex.normal_distance),
1356                f64::from(vertex.normal_distance),
1357            ),
1358        )?;
1359        Some((range_vector_scale(miter, scalar)?, within_limit))
1360    });
1361    let normal_scalar = (
1362        f64::from(vertex.normal_distance),
1363        f64::from(vertex.normal_distance),
1364    );
1365    let tangent_scalar = (
1366        f64::from(vertex.tangent_distance),
1367        f64::from(vertex.tangent_distance),
1368    );
1369    let next_normal_offset = range_vector_scale(next_normal, normal_scalar)?;
1370    let previous_normal_offset = range_vector_scale(previous_normal, normal_scalar)?;
1371    let tangent_offset = range_vector_scale(next_tangent, tangent_scalar)?;
1372    let mut inactive_candidate = false;
1373    let mut extrusion = range_vector_add(next_normal_offset, tangent_offset)?;
1374    if (1.0..=3.0).contains(&vertex.stroke_role) {
1375        if turn_sign == 0.0 {
1376            extrusion = next_normal_offset;
1377        } else {
1378            let side = vertex.normal_distance.signum();
1379            let outer_side = -turn_sign;
1380            if side * outer_side <= 0.0 {
1381                extrusion = miter_state
1382                    .filter(|state| state.1)
1383                    .map_or([(0.0, 0.0); 2], |state| state.0);
1384            } else if vertex.stroke_role == 2.0 && miter_state.is_some_and(|state| state.1) {
1385                extrusion = miter_state?.0;
1386            } else if vertex.stroke_parameter < 0.0 {
1387                extrusion = previous_normal_offset;
1388            } else {
1389                extrusion = next_normal_offset;
1390            }
1391        }
1392        extrusion = range_vector_add(extrusion, tangent_offset)?;
1393    } else if vertex.stroke_role >= 4.0 {
1394        let inner = matches!(vertex.stroke_role as i32, 5 | 7 | 9);
1395        let side = vertex.normal_distance.signum();
1396        let candidate_side = if inner { -side } else { side };
1397        let mut active = turn_sign != 0.0 && candidate_side * -turn_sign > 0.0;
1398        if matches!(vertex.stroke_role as i32, 6 | 7) {
1399            active &= miter_state.is_none_or(|state| !state.1);
1400        }
1401        if !active {
1402            inactive_candidate = true;
1403            extrusion = [(0.0, 0.0); 2];
1404        } else if inner {
1405            extrusion = miter_state
1406                .filter(|state| state.1)
1407                .map_or([(0.0, 0.0); 2], |state| state.0);
1408        } else if vertex.stroke_role == 8.0 {
1409            let side_range = (f64::from(candidate_side), f64::from(candidate_side));
1410            let start = range_vector_scale(previous_normal, side_range)?;
1411            let finish = range_vector_scale(next_normal, side_range)?;
1412            let amount = f64::from(vertex.stroke_parameter);
1413            let mixed = range_vector_add(
1414                range_vector_scale(start, (1.0 - amount, 1.0 - amount))?,
1415                range_vector_scale(finish, (amount, amount))?,
1416            )?;
1417            extrusion = range_vector_scale(
1418                stroke_safe_unit_range(mixed)?,
1419                (
1420                    f64::from(vertex.normal_distance.abs()),
1421                    f64::from(vertex.normal_distance.abs()),
1422                ),
1423            )?;
1424        } else if vertex.stroke_parameter < 0.0 {
1425            extrusion = previous_normal_offset;
1426        } else {
1427            extrusion = next_normal_offset;
1428        }
1429    } else if miter_state.is_some_and(|state| state.1) {
1430        extrusion = range_vector_add(miter_state?.0, tangent_offset)?;
1431    }
1432    let screen = range_vector_add(base, extrusion)?;
1433    let screen_offset = [
1434        (
1435            f64::from(vertex.screen_offset[0]),
1436            f64::from(vertex.screen_offset[0]),
1437        ),
1438        (
1439            f64::from(vertex.screen_offset[1]),
1440            f64::from(vertex.screen_offset[1]),
1441        ),
1442    ];
1443    Some((range_vector_add(screen, screen_offset)?, inactive_candidate))
1444}
1445
1446fn range_vector_add(left: [(f64, f64); 2], right: [(f64, f64); 2]) -> Option<[(f64, f64); 2]> {
1447    Some([
1448        rounded_f32_add_range(left[0], right[0], false)?,
1449        rounded_f32_add_range(left[1], right[1], false)?,
1450    ])
1451}
1452
1453fn range_vector_scale(vector: [(f64, f64); 2], scalar: (f64, f64)) -> Option<[(f64, f64); 2]> {
1454    Some([
1455        rounded_f32_product_range(vector[0], scalar)?,
1456        rounded_f32_product_range(vector[1], scalar)?,
1457    ])
1458}
1459
1460fn range_dot(left: [(f64, f64); 2], right: [(f64, f64); 2]) -> Option<(f64, f64)> {
1461    rounded_f32_add_range(
1462        rounded_f32_product_range(left[0], right[0])?,
1463        rounded_f32_product_range(left[1], right[1])?,
1464        false,
1465    )
1466}
1467
1468fn range_negate(value: (f64, f64)) -> (f64, f64) {
1469    (-value.1, -value.0)
1470}
1471
1472fn range_abs(value: (f64, f64)) -> (f64, f64) {
1473    if value.0 <= 0.0 && value.1 >= 0.0 {
1474        (0.0, value.0.abs().max(value.1.abs()))
1475    } else {
1476        (
1477            value.0.abs().min(value.1.abs()),
1478            value.0.abs().max(value.1.abs()),
1479        )
1480    }
1481}
1482
1483fn stroke_safe_unit_range(direction: [(f64, f64); 2]) -> Option<[(f64, f64); 2]> {
1484    let horizontal_abs = range_abs(direction[0]);
1485    let vertical_abs = range_abs(direction[1]);
1486    let scale = (
1487        horizontal_abs.0.max(vertical_abs.0),
1488        horizontal_abs.1.max(vertical_abs.1),
1489    );
1490    if scale.0 < f64::from(f32::MIN_POSITIVE) {
1491        return None;
1492    }
1493    let scaled = [
1494        rounded_f32_division_range(direction[0], scale)?,
1495        rounded_f32_division_range(direction[1], scale)?,
1496    ];
1497    let length_squared = range_dot(scaled, scaled)?;
1498    if length_squared.0 < f64::from(f32::MIN_POSITIVE) {
1499        return None;
1500    }
1501    let mut inverse_length =
1502        rounded_f32_range(1.0 / length_squared.1.sqrt(), 1.0 / length_squared.0.sqrt())?;
1503    // WGSL permits two ULP error for inverseSqrt. Add two outward neighbours;
1504    // an inexact endpoint may already carry one additional rounding neighbour.
1505    for _ in 0..2 {
1506        inverse_length = (
1507            f64::from(next_f32_down(inverse_length.0 as f32)?),
1508            f64::from(next_f32_up(inverse_length.1 as f32)?),
1509        );
1510    }
1511    range_vector_scale(scaled, inverse_length)
1512}
1513
1514fn rounded_f32_division_range(
1515    numerator: (f64, f64),
1516    denominator: (f64, f64),
1517) -> Option<(f64, f64)> {
1518    if denominator.0 <= 0.0 && denominator.1 >= 0.0 {
1519        return None;
1520    }
1521    let quotients = [
1522        numerator.0 / denominator.0,
1523        numerator.0 / denominator.1,
1524        numerator.1 / denominator.0,
1525        numerator.1 / denominator.1,
1526    ];
1527    let mut range = rounded_f32_range(
1528        quotients.into_iter().fold(f64::INFINITY, f64::min),
1529        quotients.into_iter().fold(f64::NEG_INFINITY, f64::max),
1530    )?;
1531    // WGSL permits 2.5 ULP division error. Three outward neighbours cover it;
1532    // an inexact endpoint may already carry one additional rounding neighbour.
1533    for _ in 0..3 {
1534        range = (
1535            f64::from(next_f32_down(range.0 as f32)?),
1536            f64::from(next_f32_up(range.1 as f32)?),
1537        );
1538    }
1539    Some(range)
1540}
1541
1542fn rounded_f32_product_range(left: (f64, f64), right: (f64, f64)) -> Option<(f64, f64)> {
1543    let products = [
1544        left.0 * right.0,
1545        left.0 * right.1,
1546        left.1 * right.0,
1547        left.1 * right.1,
1548    ];
1549    rounded_f32_range(
1550        products.into_iter().fold(f64::INFINITY, f64::min),
1551        products.into_iter().fold(f64::NEG_INFINITY, f64::max),
1552    )
1553}
1554
1555fn rounded_f32_add_range(
1556    left: (f64, f64),
1557    right: (f64, f64),
1558    subtract: bool,
1559) -> Option<(f64, f64)> {
1560    let (minimum, maximum) = if subtract {
1561        (left.0 - right.1, left.1 - right.0)
1562    } else {
1563        (left.0 + right.0, left.1 + right.1)
1564    };
1565    rounded_f32_range(minimum, maximum)
1566}
1567
1568fn rounded_f32_range(minimum: f64, maximum: f64) -> Option<(f64, f64)> {
1569    if !minimum.is_finite()
1570        || !maximum.is_finite()
1571        || minimum < -f64::from(MAX_PORTABLE_SHADER_VALUE)
1572        || maximum > f64::from(MAX_PORTABLE_SHADER_VALUE)
1573    {
1574        return None;
1575    }
1576    if minimum == maximum && f64::from(minimum as f32) == minimum {
1577        return Some((minimum, maximum));
1578    }
1579    let mut minimum = f64::from(next_f32_down(minimum as f32)?);
1580    let mut maximum = f64::from(next_f32_up(maximum as f32)?);
1581    let minimum_normal = f64::from(f32::MIN_POSITIVE);
1582    if maximum > 0.0 && minimum < minimum_normal {
1583        minimum = minimum.min(0.0);
1584    }
1585    if minimum < 0.0 && maximum > -minimum_normal {
1586        maximum = maximum.max(0.0);
1587    }
1588    Some((minimum, maximum))
1589}
1590
1591fn next_f32_down(value: f32) -> Option<f32> {
1592    if !value.is_finite() {
1593        return None;
1594    }
1595    let next = if value == 0.0 {
1596        -f32::from_bits(1)
1597    } else if value > 0.0 {
1598        f32::from_bits(value.to_bits().checked_sub(1)?)
1599    } else {
1600        f32::from_bits(value.to_bits().checked_add(1)?)
1601    };
1602    next.is_finite().then_some(next)
1603}
1604
1605fn next_f32_up(value: f32) -> Option<f32> {
1606    if !value.is_finite() {
1607        return None;
1608    }
1609    let next = if value == 0.0 {
1610        f32::from_bits(1)
1611    } else if value > 0.0 {
1612        f32::from_bits(value.to_bits().checked_add(1)?)
1613    } else {
1614        f32::from_bits(value.to_bits().checked_sub(1)?)
1615    };
1616    next.is_finite().then_some(next)
1617}
1618
1619fn screen_ranges_to_clip(
1620    screen: [(f64, f64); 2],
1621    uniform: CameraUniform,
1622) -> Option<[(f64, f64); 2]> {
1623    Some([
1624        shader_interval_sum_range([
1625            interval_products_f64(uniform.screen_to_clip[0], screen[0].0, screen[0].1),
1626            (
1627                f64::from(uniform.screen_to_clip[2]),
1628                f64::from(uniform.screen_to_clip[2]),
1629            ),
1630        ])?,
1631        shader_interval_sum_range([
1632            interval_products_f64(uniform.screen_to_clip[1], screen[1].0, screen[1].1),
1633            (
1634                f64::from(uniform.screen_to_clip[3]),
1635                f64::from(uniform.screen_to_clip[3]),
1636            ),
1637        ])?,
1638    ])
1639}
1640
1641fn shader_interval_difference(left: (f64, f64), right: (f64, f64)) -> Option<(f64, f64)> {
1642    shader_interval_sum_range([left, (-right.1, -right.0)])
1643}
1644
1645fn shader_interval_product(left: (f64, f64), right: (f64, f64)) -> Option<(f64, f64)> {
1646    let products = [
1647        left.0 * right.0,
1648        left.0 * right.1,
1649        left.1 * right.0,
1650        left.1 * right.1,
1651    ];
1652    shader_interval_sum_range([(
1653        products.into_iter().fold(f64::INFINITY, f64::min),
1654        products.into_iter().fold(f64::NEG_INFINITY, f64::max),
1655    )])
1656}
1657
1658fn geometry_vertex_centers_are_portable(
1659    source: GeometryValidationSource<'_>,
1660    uniform: CameraUniform,
1661) -> bool {
1662    let dynamic_center_is_portable = |world: [f32; 2], depth: f32| {
1663        let Some(relative_x) = shader_relative_component_bounds(
1664            world[0],
1665            world[0],
1666            uniform.camera_center[0],
1667            0.0,
1668            0.0,
1669        ) else {
1670            return false;
1671        };
1672        let Some(relative_y) = shader_relative_component_bounds(
1673            world[1],
1674            world[1],
1675            uniform.camera_center[1],
1676            0.0,
1677            0.0,
1678        ) else {
1679            return false;
1680        };
1681        let minimum = [relative_x.0, relative_y.0];
1682        let maximum = [relative_x.1, relative_y.1];
1683        shader_world_dot_range(uniform.world_to_screen_x, minimum, maximum, depth, depth).is_some()
1684            && shader_world_dot_range(uniform.world_to_screen_y, minimum, maximum, depth, depth)
1685                .is_some()
1686    };
1687    match source {
1688        GeometryValidationSource::Tessellated(vertices) => vertices
1689            .iter()
1690            .all(|vertex| tessellated_vertex_clip_ranges(*vertex, uniform).is_some()),
1691        GeometryValidationSource::Dynamic(vertices) => vertices
1692            .iter()
1693            .all(|vertex| dynamic_center_is_portable(vertex.world_position, vertex.depth)),
1694    }
1695}
1696
1697fn geometry_sources_are_portable(source: GeometryValidationSource<'_>) -> bool {
1698    match source {
1699        GeometryValidationSource::Tessellated(vertices) => vertices.iter().all(|vertex| {
1700            vertex
1701                .world_position
1702                .into_iter()
1703                .chain(vertex.world_offset)
1704                .chain(vertex.screen_offset)
1705                .chain(vertex.previous_direction)
1706                .chain(vertex.next_direction)
1707                .chain([
1708                    vertex.depth,
1709                    vertex.normal_distance,
1710                    vertex.tangent_distance,
1711                    vertex.miter_limit,
1712                ])
1713                .all(is_portable_shader_source)
1714        }),
1715        GeometryValidationSource::Dynamic(vertices) => vertices.iter().all(|vertex| {
1716            vertex
1717                .world_position
1718                .into_iter()
1719                .chain([vertex.depth])
1720                .all(is_portable_shader_source)
1721        }),
1722    }
1723}
1724
1725fn logical_stroke_branches_are_stable(vertex: Vertex, uniform: CameraUniform) -> bool {
1726    if vertex.normal_distance == 0.0 && vertex.tangent_distance == 0.0 {
1727        return true;
1728    }
1729    let project = |direction: [f32; 2]| {
1730        [
1731            f64::from(uniform.world_to_screen_x[0]) * f64::from(direction[0])
1732                + f64::from(uniform.world_to_screen_x[1]) * f64::from(direction[1]),
1733            f64::from(uniform.world_to_screen_y[0]) * f64::from(direction[0])
1734                + f64::from(uniform.world_to_screen_y[1]) * f64::from(direction[1]),
1735        ]
1736    };
1737    let stable_projected_direction = |direction: [f32; 2]| {
1738        let direction = Vec2::new(direction[0], direction[1]);
1739        let horizontal =
1740            shader_direction_dot_range(uniform.world_to_screen_x, direction, direction)?;
1741        let vertical = shader_direction_dot_range(uniform.world_to_screen_y, direction, direction)?;
1742        let fixed = project([direction.x, direction.y]);
1743        let component_minimum_magnitude = |range: (f64, f64)| {
1744            if range.0 > 0.0 {
1745                range.0
1746            } else if range.1 < 0.0 {
1747                -range.1
1748            } else {
1749                0.0
1750            }
1751        };
1752        let lower_length =
1753            component_minimum_magnitude(horizontal).hypot(component_minimum_magnitude(vertical));
1754        let fixed_length = fixed[0].hypot(fixed[1]);
1755        let uncertainty = (horizontal.0 - fixed[0])
1756            .abs()
1757            .max((horizontal.1 - fixed[0]).abs())
1758            .hypot(
1759                (vertical.0 - fixed[1])
1760                    .abs()
1761                    .max((vertical.1 - fixed[1]).abs()),
1762            );
1763        let minimum_normal = f64::from(f32::MIN_POSITIVE);
1764        (lower_length >= minimum_normal
1765            && fixed_length.is_finite()
1766            && uncertainty.is_finite()
1767            && uncertainty <= fixed_length * 1.0e-6)
1768            .then_some(fixed)
1769    };
1770    let Some(previous_projected) = stable_projected_direction(vertex.previous_direction) else {
1771        return false;
1772    };
1773    let Some(next_projected) = stable_projected_direction(vertex.next_direction) else {
1774        return false;
1775    };
1776    if vertex.previous_direction == vertex.next_direction {
1777        // The shader detects source equality and reuses one projection and
1778        // normalization result, so identical directions cannot acquire a
1779        // backend-dependent artificial turn.
1780        return true;
1781    }
1782
1783    let normalize = |value: [f64; 2]| {
1784        let scale = value[0].abs().max(value[1].abs());
1785        if !scale.is_finite() || scale <= 0.0 {
1786            return None;
1787        }
1788        let scaled = [value[0] / scale, value[1] / scale];
1789        let length = scaled[0].hypot(scaled[1]);
1790        (length.is_finite() && length > 0.0).then_some([scaled[0] / length, scaled[1] / length])
1791    };
1792    let Some(previous) = normalize(previous_projected) else {
1793        return false;
1794    };
1795    let Some(next) = normalize(next_projected) else {
1796        return false;
1797    };
1798    let turn = previous[0] * next[1] - previous[1] * next[0];
1799    let tangent_dot = previous[0] * next[0] + previous[1] * next[1];
1800    if !turn.is_finite() || !tangent_dot.is_finite() {
1801        return false;
1802    }
1803    // Keep every topology-changing comparison far outside WGSL's permitted
1804    // normal-operation error. Exact repeated directions took the fast path.
1805    if turn.abs() <= 1.0e-4 || tangent_dot <= -0.999_9 {
1806        return false;
1807    }
1808
1809    let previous_normal = [-previous[1], previous[0]];
1810    let next_normal = [-next[1], next[0]];
1811    let combined = [
1812        previous_normal[0] + next_normal[0],
1813        previous_normal[1] + next_normal[1],
1814    ];
1815    let Some(miter) = normalize(combined) else {
1816        return false;
1817    };
1818    let denominator = miter[0] * next_normal[0] + miter[1] * next_normal[1];
1819    if !denominator.is_finite() || denominator.abs() <= 0.002 {
1820        return false;
1821    }
1822    let miter_multiple = 1.0 / denominator.abs();
1823    let limit = f64::from(vertex.miter_limit);
1824    let comparison_margin = 1.0e-4 * miter_multiple.abs().max(limit.abs()).max(1.0);
1825    (miter_multiple - limit).abs() > comparison_margin
1826}
1827
1828fn shader_clip_interval_is_safe(
1829    screen_minimum: f64,
1830    screen_maximum: f64,
1831    scale: f32,
1832    offset: f32,
1833) -> bool {
1834    if ((is_nonzero_subnormal_f64(screen_minimum) || is_nonzero_subnormal_f64(screen_maximum))
1835        && scale != 0.0)
1836        || (is_nonzero_subnormal(scale) && (screen_minimum != 0.0 || screen_maximum != 0.0))
1837    {
1838        return false;
1839    }
1840    shader_interval_sum_range([
1841        interval_products_f64(scale, screen_minimum, screen_maximum),
1842        (f64::from(offset), f64::from(offset)),
1843    ])
1844    .is_some()
1845}
1846
1847fn shader_relative_component_bounds(
1848    world_minimum: f32,
1849    world_maximum: f32,
1850    camera_center: f32,
1851    offset_minimum: f32,
1852    offset_maximum: f32,
1853) -> Option<(f64, f64)> {
1854    // Exact equal f32 operands subtract to exact zero on every backend. Keep
1855    // that important camera-relative case tight so separately projected local
1856    // tessellation offsets remain usable at large world anchors.
1857    let subtraction = if world_minimum == camera_center && world_maximum == camera_center {
1858        (0.0, 0.0)
1859    } else {
1860        shader_interval_sum_range([
1861            (f64::from(world_minimum), f64::from(world_maximum)),
1862            (-f64::from(camera_center), -f64::from(camera_center)),
1863        ])?
1864    };
1865    if offset_minimum == 0.0 && offset_maximum == 0.0 {
1866        Some(subtraction)
1867    } else {
1868        shader_interval_sum_range([
1869            subtraction,
1870            (f64::from(offset_minimum), f64::from(offset_maximum)),
1871        ])
1872    }
1873}
1874
1875fn shader_world_dot_range(
1876    row: [f32; 4],
1877    minimum: [f64; 2],
1878    maximum: [f64; 2],
1879    depth_minimum: f32,
1880    depth_maximum: f32,
1881) -> Option<(f64, f64)> {
1882    if (is_nonzero_subnormal(row[0]) && (minimum[0] != 0.0 || maximum[0] != 0.0))
1883        || (is_nonzero_subnormal(row[1]) && (minimum[1] != 0.0 || maximum[1] != 0.0))
1884        || (is_nonzero_subnormal(row[2]) && (depth_minimum != 0.0 || depth_maximum != 0.0))
1885        || ((is_nonzero_subnormal_f64(minimum[0]) || is_nonzero_subnormal_f64(maximum[0]))
1886            && row[0] != 0.0)
1887        || ((is_nonzero_subnormal_f64(minimum[1]) || is_nonzero_subnormal_f64(maximum[1]))
1888            && row[1] != 0.0)
1889        || ((is_nonzero_subnormal(depth_minimum) || is_nonzero_subnormal(depth_maximum))
1890            && row[2] != 0.0)
1891    {
1892        return None;
1893    }
1894    shader_interval_sum_range([
1895        interval_products_f64(row[0], minimum[0], maximum[0]),
1896        interval_products_f64(row[1], minimum[1], maximum[1]),
1897        interval_products(row[2], depth_minimum, depth_maximum),
1898        (f64::from(row[3]), f64::from(row[3])),
1899    ])
1900}
1901
1902fn shader_direction_dot_range(row: [f32; 4], minimum: Vec2, maximum: Vec2) -> Option<(f64, f64)> {
1903    if (is_nonzero_subnormal(row[0]) && (minimum.x != 0.0 || maximum.x != 0.0))
1904        || (is_nonzero_subnormal(row[1]) && (minimum.y != 0.0 || maximum.y != 0.0))
1905        || ((is_nonzero_subnormal(minimum.x) || is_nonzero_subnormal(maximum.x)) && row[0] != 0.0)
1906        || ((is_nonzero_subnormal(minimum.y) || is_nonzero_subnormal(maximum.y)) && row[1] != 0.0)
1907    {
1908        return None;
1909    }
1910    shader_interval_sum_range([
1911        interval_products(row[0], minimum.x, maximum.x),
1912        interval_products(row[1], minimum.y, maximum.y),
1913    ])
1914}
1915
1916#[cfg(test)]
1917fn shader_interval_sum_is_safe<const N: usize>(terms: [(f64, f64); N]) -> bool {
1918    shader_interval_sum_range(terms).is_some()
1919}
1920
1921fn shader_interval_sum_range<const N: usize>(terms: [(f64, f64); N]) -> Option<(f64, f64)> {
1922    // WGSL's `dot` may be lowered with a backend-selected association or FMA
1923    // pattern. Bound all multiplication/addition rounding as well as every
1924    // same-sign partial sum, then return the complete finite output interval.
1925    // Keeping that interval is essential when a later shader stage multiplies
1926    // a cancellation residual by another large coefficient.
1927    let maximum = f64::from(MAX_PORTABLE_SHADER_VALUE);
1928    let mut positive_sum = 0.0;
1929    let mut negative_sum = 0.0;
1930    let mut minimum_sum = 0.0;
1931    let mut maximum_sum = 0.0;
1932    let mut magnitude_sum = 0.0;
1933    for term in terms {
1934        // WGSL permits implementations to flush subnormal arithmetic to zero.
1935        // A flushed product can become visually significant after a later
1936        // large camera or clip multiplier, so reject it structurally.
1937        if is_nonzero_subnormal_f64(term.0)
1938            || is_nonzero_subnormal_f64(term.1)
1939            || !term.0.is_finite()
1940            || !term.1.is_finite()
1941            || term.0 < -maximum
1942            || term.1 > maximum
1943        {
1944            return None;
1945        }
1946        positive_sum += term.1.max(0.0);
1947        negative_sum += term.0.min(0.0);
1948        minimum_sum += term.0;
1949        maximum_sum += term.1;
1950        magnitude_sum += term.0.abs().max(term.1.abs());
1951    }
1952
1953    // Exact zero terms do not participate in any association, and an isolated
1954    // exactly representable product needs no rounding allowance. This keeps
1955    // component-selection rows tight inside the portability envelope while
1956    // retaining a conservative margin for operations which can round.
1957    let active_terms = terms
1958        .iter()
1959        .filter(|term| term.0 != 0.0 || term.1 != 0.0)
1960        .count();
1961    if active_terms == 1 {
1962        let term = terms
1963            .into_iter()
1964            .find(|term| term.0 != 0.0 || term.1 != 0.0)?;
1965        // A single interval term has no association ambiguity. When both
1966        // endpoints are already representable f32 values, they also prove
1967        // that the producing multiply rounded exactly at the extrema; adding
1968        // the remaining exact zero terms cannot enlarge the range. This is
1969        // important for a later dot row which merely selects or negates one
1970        // component from an earlier association envelope.
1971        if [term.0, term.1]
1972            .into_iter()
1973            .all(|value| f64::from(value as f32) == value)
1974        {
1975            return Some(term);
1976        }
1977    }
1978    let inexact_products = terms
1979        .iter()
1980        .filter(|term| {
1981            term.0 != term.1 || !term.0.is_finite() || f64::from(term.0 as f32) != term.0
1982        })
1983        .count();
1984    let operation_count = inexact_products + active_terms.saturating_sub(1);
1985    let operation_count = operation_count as f64;
1986    // WGSL correctly-rounded operations may select either adjacent f32 value;
1987    // use the directed-rounding bound rather than Rust's round-to-nearest.
1988    let unit_roundoff = 2.0_f64.powi(-23);
1989    let gamma = operation_count * unit_roundoff / (1.0 - operation_count * unit_roundoff);
1990    let subnormal_margin = if magnitude_sum > 0.0 {
1991        operation_count * f64::from(f32::MIN_POSITIVE)
1992    } else {
1993        0.0
1994    };
1995    let rounding_margin = gamma * magnitude_sum + subnormal_margin;
1996    let minimum_output = minimum_sum - rounding_margin;
1997    let maximum_output = maximum_sum + rounding_margin;
1998    if !positive_sum.is_finite()
1999        || !negative_sum.is_finite()
2000        || !minimum_output.is_finite()
2001        || !maximum_output.is_finite()
2002        || positive_sum + rounding_margin > maximum
2003        || negative_sum - rounding_margin < -maximum
2004        || minimum_output < -maximum
2005        || maximum_output > maximum
2006    {
2007        return None;
2008    }
2009    Some((minimum_output, maximum_output))
2010}
2011
2012fn is_nonzero_subnormal(value: f32) -> bool {
2013    value != 0.0 && value.abs() < f32::MIN_POSITIVE
2014}
2015
2016fn is_nonzero_subnormal_f64(value: f64) -> bool {
2017    value != 0.0 && value.abs() < f64::from(f32::MIN_POSITIVE)
2018}
2019
2020fn interval_products(coefficient: f32, minimum: f32, maximum: f32) -> (f64, f64) {
2021    interval_products_f64(coefficient, f64::from(minimum), f64::from(maximum))
2022}
2023
2024fn interval_products_f64(coefficient: f32, minimum: f64, maximum: f64) -> (f64, f64) {
2025    let first = f64::from(coefficient) * minimum;
2026    let second = f64::from(coefficient) * maximum;
2027    (first.min(second), first.max(second))
2028}
2029
2030/// Result of attempting to draw a frame.
2031#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2032pub enum RenderStatus {
2033    /// Commands were submitted successfully. Surface paths also requested
2034    /// presentation; offscreen paths completed their target submission only.
2035    Drawn,
2036    /// The frame was skipped because the window surface was temporarily unavailable.
2037    Skipped(RendererSurfaceStatus),
2038}
2039
2040/// CPU-side durations measured while preparing and submitting one renderer frame.
2041///
2042/// These values do not measure GPU execution or the monitor scanout timestamp.
2043/// FIFO presentation back-pressure normally appears in `surface_acquire` because
2044/// `wgpu` blocks frame acquisition when the presentation queue is full.
2045#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2046pub struct RendererFrameMetrics {
2047    tessellation: Duration,
2048    upload: Duration,
2049    camera_uniform_upload: Duration,
2050    surface_acquire: Duration,
2051    encode_submit_present: Duration,
2052    total_cpu: Duration,
2053    geometry_reused: bool,
2054    geometry_streamed: bool,
2055    tessellation_stats: TessellationStats,
2056}
2057
2058impl RendererFrameMetrics {
2059    /// Returns CPU time spent preparing visual work before GPU uploads.
2060    ///
2061    /// For an ordinary streaming scene this is validation and tessellation.
2062    /// A heterogeneous [`FrameComposer`](crate::FrameComposer) frame also
2063    /// includes viewport and source validation, particle visibility selection,
2064    /// scalar LUT generation, and preparation of retained image/glyph draws.
2065    pub fn tessellation(self) -> Duration {
2066        self.tessellation
2067    }
2068
2069    /// Returns CPU time spent preparing and enqueueing non-camera per-frame GPU data.
2070    ///
2071    /// Depending on the rendering path this includes transient vertex or
2072    /// instance writes, scalar LUT and pass-uniform uploads, and creation of
2073    /// the per-frame bindings needed by image, glyph, scalar, particle, or
2074    /// composition passes. The camera-only write remains separately available
2075    /// through [`Self::camera_uniform_upload`]. This is CPU preparation/enqueue
2076    /// time, not GPU execution time. An ordinary streaming frame can include
2077    /// pre-acquire transient buffer
2078    /// capacity creation here, so a skipped report may have a non-zero duration
2079    /// even though it performed no queue write and reports zero uploaded bytes.
2080    pub fn upload(self) -> Duration {
2081        self.upload
2082    }
2083
2084    /// Returns CPU time spent updating the small per-frame camera uniform.
2085    pub fn camera_uniform_upload(self) -> Duration {
2086        self.camera_uniform_upload
2087    }
2088
2089    /// Returns CPU time spent acquiring the next presentation surface texture.
2090    ///
2091    /// In FIFO modes this includes queue back-pressure and is the closest CPU-side
2092    /// approximation to VSync wait exposed by `wgpu`.
2093    pub fn surface_acquire(self) -> Duration {
2094        self.surface_acquire
2095    }
2096
2097    /// Returns CPU time spent encoding, submitting, and dispatching present.
2098    ///
2099    /// Present dispatch does not mean the monitor has already scanned out the
2100    /// frame; `wgpu` does not expose that timestamp here.
2101    pub fn encode_submit_present(self) -> Duration {
2102        self.encode_submit_present
2103    }
2104
2105    /// Returns total CPU time inside the profiled render call.
2106    pub fn total_cpu(self) -> Duration {
2107        self.total_cpu
2108    }
2109
2110    /// Returns whether this frame referenced retained visual geometry.
2111    ///
2112    /// This includes prepared scenes and retained sprite/glyph batches. It is
2113    /// a broad workload-classification hint rather than a statement that the
2114    /// frame performed no uploads, and it can be true together with
2115    /// [`Self::geometry_streamed`].
2116    pub fn geometry_reused(self) -> bool {
2117        self.geometry_reused
2118    }
2119
2120    /// Returns whether this frame contained dynamically supplied visual work.
2121    ///
2122    /// This includes dynamic meshes, particle visibility instances, and scalar
2123    /// field passes. It is a broad workload-classification hint rather than an
2124    /// allocation or upload guarantee, and it can be true together with
2125    /// [`Self::geometry_reused`].
2126    pub fn geometry_streamed(self) -> bool {
2127        self.geometry_streamed
2128    }
2129
2130    /// Returns command-level tessellation results for this frame.
2131    pub fn tessellation_stats(self) -> TessellationStats {
2132        self.tessellation_stats
2133    }
2134}
2135
2136/// Status and CPU timing breakdown for one renderer frame.
2137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2138pub struct RenderReport {
2139    status: RenderStatus,
2140    metrics: RendererFrameMetrics,
2141}
2142
2143impl RenderReport {
2144    /// Returns whether the frame was drawn or skipped by the surface.
2145    pub fn status(self) -> RenderStatus {
2146        self.status
2147    }
2148
2149    /// Returns CPU-side stage durations for the render call.
2150    pub fn metrics(self) -> RendererFrameMetrics {
2151        self.metrics
2152    }
2153}
2154
2155/// Recoverable or fatal state reported by the presentation surface.
2156#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2157pub enum RendererSurfaceStatus {
2158    /// Acquiring the next frame timed out; try again on a later frame.
2159    Timeout,
2160    /// The surface is occluded or minimized; rendering can be skipped.
2161    Occluded,
2162    /// The surface configuration is stale; resizing or reconfiguring is needed.
2163    Outdated,
2164    /// The surface was lost and should be recreated by the host application.
2165    Lost,
2166    /// `wgpu` reported a validation error while acquiring the frame.
2167    Validation,
2168}
2169
2170/// Fatal failure while preparing or submitting one frame.
2171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2172pub enum RendererFrameError {
2173    /// The presentation surface was lost or rejected frame acquisition.
2174    Surface(RendererSurfaceStatus),
2175    /// Camera, geometry, stroke arithmetic, or dynamic-triangle topology
2176    /// cannot be proven portable on the GPU.
2177    ///
2178    /// This includes nonzero subnormal or excessively large shader sources,
2179    /// transform ranges that may overflow under permitted GPU arithmetic, and
2180    /// stroke branch decisions that are ambiguous after projection, every
2181    /// dynamic triangle requiring partial frustum clipping, and projected
2182    /// triangle orientation that may change with legal shader association.
2183    InvalidGeometryTransform,
2184    /// A logical viewport is outside the active surface or render target.
2185    InvalidViewport,
2186    /// Tessellated geometry exceeds the active device's vertex-buffer limit.
2187    GeometryCapacityTooLarge,
2188    /// CPU storage for scene tessellation could not be reserved.
2189    SceneAllocationFailed {
2190        /// Minimum additional bytes requested by the failed reservation.
2191        requested_bytes: usize,
2192    },
2193    /// CPU storage for the camera-visible particle subset could not be reserved.
2194    ParticleAllocationFailed {
2195        /// Bytes requested for the rejected visible-instance vector.
2196        requested_bytes: usize,
2197    },
2198    /// Actual renderer work exceeded a scene's explicit limit.
2199    SceneBudgetExceeded {
2200        /// Work category whose post-tessellation limit was exceeded.
2201        resource: SceneBudgetResource,
2202        /// Configured maximum for the category.
2203        limit: usize,
2204        /// Actual renderer work observed.
2205        actual: usize,
2206    },
2207}
2208
2209impl fmt::Display for RendererFrameError {
2210    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2211        match self {
2212            Self::Surface(status) => write!(formatter, "renderer surface failed: {status:?}"),
2213            Self::InvalidGeometryTransform => {
2214                write!(
2215                    formatter,
2216                    "camera, geometry, or dynamic topology is outside the portable GPU envelope"
2217                )
2218            }
2219            Self::InvalidViewport => {
2220                write!(
2221                    formatter,
2222                    "logical viewport lies outside the active render target"
2223                )
2224            }
2225            Self::GeometryCapacityTooLarge => {
2226                write!(formatter, "geometry exceeds the GPU vertex-buffer limit")
2227            }
2228            Self::SceneAllocationFailed { requested_bytes } => write!(
2229                formatter,
2230                "could not reserve {requested_bytes} additional bytes for scene tessellation"
2231            ),
2232            Self::ParticleAllocationFailed { requested_bytes } => write!(
2233                formatter,
2234                "could not reserve {requested_bytes} bytes for visible particle instances"
2235            ),
2236            Self::SceneBudgetExceeded {
2237                resource,
2238                limit,
2239                actual,
2240            } => write!(
2241                formatter,
2242                "scene {resource:?} work exceeded its limit {limit} after tessellation: {actual}"
2243            ),
2244        }
2245    }
2246}
2247
2248impl Error for RendererFrameError {}
2249
2250/// Errors that can happen while creating the `wgpu` renderer.
2251#[derive(Debug)]
2252pub enum RendererInitError {
2253    /// Surface creation failed for the provided window or canvas target.
2254    CreateSurface(wgpu::CreateSurfaceError),
2255    /// No compatible GPU adapter could be selected.
2256    RequestAdapter(wgpu::RequestAdapterError),
2257    /// A logical GPU device and queue could not be created.
2258    RequestDevice(wgpu::RequestDeviceError),
2259    /// The surface did not expose a usable default configuration.
2260    NoSurfaceConfig,
2261    /// Requested physical dimensions exceed the selected device limit.
2262    SurfaceDimensionsTooLarge {
2263        /// Rejected physical width.
2264        width: u32,
2265        /// Rejected physical height.
2266        height: u32,
2267        /// Device maximum for either dimension.
2268        limit: u32,
2269    },
2270    /// The bounded previous-device quarantine is full.
2271    RecoveryLimitReached {
2272        /// Configured maximum number of quarantined logical devices.
2273        limit: usize,
2274    },
2275    /// CPU storage for quarantining the previous device could not be reserved.
2276    RecoveryAllocationFailed {
2277        /// Additional bytes requested for one quarantine entry.
2278        requested_bytes: usize,
2279    },
2280}
2281
2282impl fmt::Display for RendererInitError {
2283    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2284        match self {
2285            Self::CreateSurface(error) => write!(formatter, "failed to create surface: {error}"),
2286            Self::RequestAdapter(error) => write!(formatter, "failed to request adapter: {error}"),
2287            Self::RequestDevice(error) => write!(formatter, "failed to request device: {error}"),
2288            Self::NoSurfaceConfig => write!(formatter, "surface has no supported default config"),
2289            Self::SurfaceDimensionsTooLarge {
2290                width,
2291                height,
2292                limit,
2293            } => write!(
2294                formatter,
2295                "surface dimensions {width}x{height} exceed device limit {limit}"
2296            ),
2297            Self::RecoveryLimitReached { limit } => write!(
2298                formatter,
2299                "device recovery limit reached with {limit} quarantined devices"
2300            ),
2301            Self::RecoveryAllocationFailed { requested_bytes } => write!(
2302                formatter,
2303                "could not reserve {requested_bytes} bytes for device recovery quarantine"
2304            ),
2305        }
2306    }
2307}
2308
2309impl Error for RendererInitError {}
2310
2311/// Invalid runtime or initialization configuration for [`WgpuRenderer`].
2312#[derive(Debug, Clone, Copy, PartialEq)]
2313pub enum RendererConfigurationError {
2314    /// Logical-to-physical scale must keep all surface transforms normal and finite.
2315    InvalidScaleFactor {
2316        /// Rejected physical pixels per logical screen pixel.
2317        scale_factor: f64,
2318    },
2319    /// Previous-device quarantine must remain inside the supported bounded range.
2320    InvalidRecoveryLimit {
2321        /// Rejected maximum retained-device count.
2322        limit: usize,
2323    },
2324    /// Requested physical dimensions exceed the active device limit.
2325    SurfaceDimensionsTooLarge {
2326        /// Rejected physical width.
2327        width: u32,
2328        /// Rejected physical height.
2329        height: u32,
2330        /// Device maximum for either dimension.
2331        limit: u32,
2332    },
2333}
2334
2335impl fmt::Display for RendererConfigurationError {
2336    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2337        match self {
2338            Self::InvalidScaleFactor { scale_factor } => write!(
2339                formatter,
2340                "renderer scale factor must be finite, representable as f32, and keep every u32 surface transform in the normal f32 range, got {scale_factor}"
2341            ),
2342            Self::InvalidRecoveryLimit { limit } => write!(
2343                formatter,
2344                "renderer recovery quarantine must retain between 1 and 8 devices, got {limit}"
2345            ),
2346            Self::SurfaceDimensionsTooLarge {
2347                width,
2348                height,
2349                limit,
2350            } => write!(
2351                formatter,
2352                "surface dimensions {width}x{height} exceed device limit {limit}"
2353            ),
2354        }
2355    }
2356}
2357
2358impl Error for RendererConfigurationError {}
2359
2360/// Failure while converting between logical and physical screen coordinates.
2361#[derive(Debug, Clone, Copy, PartialEq)]
2362pub enum RendererCoordinateError {
2363    /// The source position is non-finite or the scaled result cannot be represented as `f32`.
2364    NonFiniteConversion,
2365}
2366
2367impl fmt::Display for RendererCoordinateError {
2368    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2369        write!(
2370            formatter,
2371            "screen coordinate conversion produced a non-finite result"
2372        )
2373    }
2374}
2375
2376impl Error for RendererCoordinateError {}
2377
2378/// Failure while uploading or restoring immutable prepared-scene geometry.
2379#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2380pub enum PreparedSceneError {
2381    /// Tessellated geometry exceeds the active device's vertex-buffer limit.
2382    CapacityTooLarge,
2383    /// Command sources or derived tessellated vertices are outside the
2384    /// portable GPU input envelope.
2385    InvalidGeometrySources,
2386    /// CPU storage for scene tessellation could not be reserved.
2387    AllocationFailed {
2388        /// Minimum additional bytes requested by the failed reservation.
2389        requested_bytes: usize,
2390    },
2391    /// Actual prepared-scene work exceeded an explicit scene limit.
2392    BudgetExceeded {
2393        /// Work category whose post-tessellation limit was exceeded.
2394        resource: SceneBudgetResource,
2395        /// Configured maximum for the category.
2396        limit: usize,
2397        /// Actual renderer work observed.
2398        actual: usize,
2399    },
2400}
2401
2402impl fmt::Display for PreparedSceneError {
2403    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2404        match self {
2405            Self::CapacityTooLarge => {
2406                write!(
2407                    formatter,
2408                    "prepared scene exceeds the GPU vertex-buffer limit"
2409                )
2410            }
2411            Self::InvalidGeometrySources => write!(
2412                formatter,
2413                "prepared scene contains non-portable GPU geometry sources"
2414            ),
2415            Self::AllocationFailed { requested_bytes } => write!(
2416                formatter,
2417                "could not reserve {requested_bytes} additional bytes for prepared-scene tessellation"
2418            ),
2419            Self::BudgetExceeded {
2420                resource,
2421                limit,
2422                actual,
2423            } => write!(
2424                formatter,
2425                "prepared scene {resource:?} work exceeded its limit {limit}: {actual}"
2426            ),
2427        }
2428    }
2429}
2430
2431impl From<TessellationError> for RendererFrameError {
2432    fn from(error: TessellationError) -> Self {
2433        match error {
2434            TessellationError::AllocationFailed { requested_bytes } => {
2435                Self::SceneAllocationFailed { requested_bytes }
2436            }
2437            TessellationError::CapacityTooLarge => Self::GeometryCapacityTooLarge,
2438            TessellationError::BudgetExceeded {
2439                resource,
2440                limit,
2441                actual,
2442            } => Self::SceneBudgetExceeded {
2443                resource,
2444                limit,
2445                actual,
2446            },
2447        }
2448    }
2449}
2450
2451impl From<TessellationError> for PreparedSceneError {
2452    fn from(error: TessellationError) -> Self {
2453        match error {
2454            TessellationError::AllocationFailed { requested_bytes } => {
2455                Self::AllocationFailed { requested_bytes }
2456            }
2457            TessellationError::CapacityTooLarge => Self::CapacityTooLarge,
2458            TessellationError::BudgetExceeded {
2459                resource,
2460                limit,
2461                actual,
2462            } => Self::BudgetExceeded {
2463                resource,
2464                limit,
2465                actual,
2466            },
2467        }
2468    }
2469}
2470
2471impl Error for PreparedSceneError {}
2472
2473/// Failure to draw geometry prepared by [`WgpuRenderer::prepare_scene`].
2474#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2475pub enum PreparedSceneRenderError {
2476    /// The prepared geometry belongs to a different renderer and GPU device.
2477    RendererMismatch,
2478    /// Frame rendering failed after prepared-scene ownership validation.
2479    Frame(RendererFrameError),
2480}
2481
2482impl fmt::Display for PreparedSceneRenderError {
2483    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2484        match self {
2485            Self::RendererMismatch => {
2486                write!(formatter, "prepared scene belongs to a different renderer")
2487            }
2488            Self::Frame(error) => write!(formatter, "prepared frame failed: {error}"),
2489        }
2490    }
2491}
2492
2493impl Error for PreparedSceneRenderError {}
2494
2495/// Immutable scene geometry tessellated and uploaded once for repeated drawing.
2496///
2497/// Camera movement, zoom, rotation, projection tilt, viewport resizing, and DPI
2498/// changes do not invalidate prepared geometry. Shape, style, gradient, layer,
2499/// or clip changes require preparing a replacement. A prepared scene can only be
2500/// rendered by the [`WgpuRenderer`] that created it. Use
2501/// [`WgpuRenderer::restore_prepared_scene`] to recreate its GPU buffer for a
2502/// replacement renderer after device loss. Portable shader arithmetic is proved
2503/// once per exact camera/viewport uniform and retained in a bounded cache.
2504pub struct PreparedScene {
2505    renderer_identity: Arc<()>,
2506    background: Color,
2507    vertex_buffer: Arc<wgpu::Buffer>,
2508    vertices: Arc<Vec<Vertex>>,
2509    command_count: usize,
2510    vertex_count: usize,
2511    geometry_extents: GeometryExtents,
2512    draw_batches: Vec<PreparedDrawBatch>,
2513    tessellation: TessellationStats,
2514    geometry_validation_cache: GeometryValidationCache,
2515}
2516
2517/// Immutable prepared geometry whose positions are logical screen pixels.
2518///
2519/// This distinct wrapper prevents a world camera from being supplied to fixed
2520/// UI geometry. It is created by [`WgpuRenderer::prepare_screen_scene`].
2521pub struct PreparedScreenScene {
2522    scene: PreparedScene,
2523}
2524
2525/// One world-space vertex in a dynamic triangle-list mesh.
2526///
2527/// Dynamic meshes use plain filled triangles. Positions are measured in world
2528/// units, `depth` uses the active camera projection, and colors are linear RGBA.
2529#[derive(Debug, Clone, Copy, PartialEq)]
2530pub struct DynamicVertex2d {
2531    world_position: Vec2,
2532    depth: f32,
2533    color: Color,
2534}
2535
2536impl DynamicVertex2d {
2537    /// Builds a finite dynamic vertex.
2538    pub fn new(world_position: Vec2, depth: f32, color: Color) -> Result<Self, DynamicMeshError> {
2539        if !world_position.is_finite() || !depth.is_finite() || !color.is_normalized() {
2540            return Err(DynamicMeshError::InvalidVertex);
2541        }
2542        Ok(Self {
2543            world_position,
2544            depth,
2545            color,
2546        })
2547    }
2548
2549    /// Returns the world-space triangle position.
2550    pub fn world_position(self) -> Vec2 {
2551        self.world_position
2552    }
2553
2554    /// Returns pseudo-depth in caller-defined units.
2555    pub fn depth(self) -> f32 {
2556        self.depth
2557    }
2558
2559    /// Returns the linear RGBA vertex color.
2560    pub fn color(self) -> Color {
2561        self.color
2562    }
2563}
2564
2565/// Validation or ownership failure while changing a dynamic mesh.
2566#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2567pub enum DynamicMeshError {
2568    /// Triangle-list vertex counts must be divisible by three.
2569    InvalidVertexCount,
2570    /// A position/depth is outside the portable shader envelope or a color is invalid.
2571    InvalidVertex,
2572    /// A partial update lies outside the mesh's current vertex range.
2573    UpdateRangeOutOfBounds,
2574    /// The mesh belongs to a different renderer and GPU device.
2575    RendererMismatch,
2576    /// The mesh capacity exceeds the current device's vertex-buffer limit.
2577    CapacityTooLarge,
2578    /// At least one complete triangle must fit in every configured limit.
2579    InvalidBudget,
2580    /// A bounded mesh operation exceeded a host-selected limit.
2581    BudgetExceeded {
2582        /// Work category that exceeded its ceiling.
2583        resource: DynamicMeshBudgetResource,
2584        /// Configured upper bound.
2585        limit: usize,
2586        /// Required work for the requested mesh state.
2587        actual: usize,
2588    },
2589    /// CPU recovery storage could not be reserved without changing the mesh.
2590    AllocationFailed {
2591        /// Bytes requested by the failed reservation.
2592        requested_bytes: usize,
2593    },
2594}
2595
2596impl fmt::Display for DynamicMeshError {
2597    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2598        match self {
2599            Self::InvalidVertexCount => write!(
2600                formatter,
2601                "dynamic mesh vertex count must be divisible by three"
2602            ),
2603            Self::InvalidVertex => write!(
2604                formatter,
2605                "dynamic mesh positions/depth must be portable and colors normalized"
2606            ),
2607            Self::UpdateRangeOutOfBounds => write!(
2608                formatter,
2609                "dynamic mesh update range is outside the current mesh"
2610            ),
2611            Self::RendererMismatch => {
2612                write!(formatter, "dynamic mesh belongs to a different renderer")
2613            }
2614            Self::CapacityTooLarge => {
2615                write!(
2616                    formatter,
2617                    "dynamic mesh exceeds the GPU vertex-buffer limit"
2618                )
2619            }
2620            Self::InvalidBudget => write!(formatter, "dynamic mesh budget must fit one triangle"),
2621            Self::BudgetExceeded {
2622                resource,
2623                limit,
2624                actual,
2625            } => write!(
2626                formatter,
2627                "dynamic mesh {resource:?} work {actual} exceeds limit {limit}"
2628            ),
2629            Self::AllocationFailed { requested_bytes } => write!(
2630                formatter,
2631                "could not reserve {requested_bytes} bytes for dynamic mesh recovery data"
2632            ),
2633        }
2634    }
2635}
2636
2637impl Error for DynamicMeshError {}
2638
2639/// Host-selected work category constrained by [`DynamicMeshBudget`].
2640#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2641pub enum DynamicMeshBudgetResource {
2642    /// Triangle-list vertex count.
2643    Vertices,
2644    /// CPU bytes retained for exact recovery.
2645    RetainedBytes,
2646    /// GPU bytes uploaded by a full replacement.
2647    UploadBytes,
2648}
2649
2650/// Explicit retained and upload limits for caller-provided colored triangles.
2651#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2652pub struct DynamicMeshBudget {
2653    max_vertices: usize,
2654    max_retained_bytes: usize,
2655    max_upload_bytes: usize,
2656}
2657
2658impl DynamicMeshBudget {
2659    /// Creates limits large enough for at least one complete triangle.
2660    pub fn new(
2661        max_vertices: usize,
2662        max_retained_bytes: usize,
2663        max_upload_bytes: usize,
2664    ) -> Result<Self, DynamicMeshError> {
2665        let triangle_bytes = 3 * std::mem::size_of::<DynamicGpu>();
2666        if max_vertices < 3
2667            || max_retained_bytes < triangle_bytes
2668            || max_upload_bytes < triangle_bytes
2669        {
2670            return Err(DynamicMeshError::InvalidBudget);
2671        }
2672        Ok(Self {
2673            max_vertices,
2674            max_retained_bytes,
2675            max_upload_bytes,
2676        })
2677    }
2678
2679    /// Returns the maximum retained triangle-list vertex count.
2680    pub const fn max_vertices(self) -> usize {
2681        self.max_vertices
2682    }
2683
2684    /// Returns the maximum exact CPU recovery bytes.
2685    pub const fn max_retained_bytes(self) -> usize {
2686        self.max_retained_bytes
2687    }
2688
2689    /// Returns the maximum bytes uploaded by one complete replacement.
2690    pub const fn max_upload_bytes(self) -> usize {
2691        self.max_upload_bytes
2692    }
2693}
2694
2695impl Default for DynamicMeshBudget {
2696    fn default() -> Self {
2697        Self {
2698            max_vertices: 1_000_000,
2699            max_retained_bytes: 64 * 1024 * 1024,
2700            max_upload_bytes: 64 * 1024 * 1024,
2701        }
2702    }
2703}
2704
2705/// Mutable GPU triangle-list geometry for high-frequency simulation visuals.
2706///
2707/// A mesh retains its CPU vertices for validation and recreates its GPU buffer
2708/// only when a replacement exceeds its current capacity. Use
2709/// [`WgpuRenderer::update_dynamic_mesh_range`] for in-place partial updates.
2710/// Its bounded camera-validation cache is cleared by every successful mutation.
2711pub struct DynamicMesh2d {
2712    renderer_identity: Arc<()>,
2713    vertex_buffer: Arc<wgpu::Buffer>,
2714    vertices: Vec<DynamicGpu>,
2715    vertex_capacity: usize,
2716    geometry_extents: GeometryExtents,
2717    geometry_validation_cache: GeometryValidationCache,
2718    budget: Option<DynamicMeshBudget>,
2719}
2720
2721impl DynamicMesh2d {
2722    /// Returns the number of triangle-list vertices currently stored.
2723    pub fn vertex_count(&self) -> usize {
2724        self.vertices.len()
2725    }
2726
2727    /// Returns the number of vertices that fit without reallocating its GPU buffer.
2728    pub fn vertex_capacity(&self) -> usize {
2729        self.vertex_capacity
2730    }
2731
2732    /// Returns retained CPU memory used for validation and future updates.
2733    pub fn recovery_memory_bytes(&self) -> usize {
2734        self.vertices
2735            .capacity()
2736            .saturating_mul(std::mem::size_of::<DynamicGpu>())
2737    }
2738
2739    /// Returns explicit limits, or `None` for the compatibility constructor.
2740    pub const fn budget(&self) -> Option<DynamicMeshBudget> {
2741        self.budget
2742    }
2743}
2744
2745/// CPU-side outcome of one dynamic mesh update.
2746#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2747pub struct DynamicMeshUpdateReport {
2748    vertex_count: usize,
2749    upload: Duration,
2750    reallocated: bool,
2751}
2752
2753impl DynamicMeshUpdateReport {
2754    /// Returns the current triangle-list vertex count after the update.
2755    pub fn vertex_count(self) -> usize {
2756        self.vertex_count
2757    }
2758
2759    /// Returns CPU time spent validating, allocating when needed, and writing GPU data.
2760    pub fn upload(self) -> Duration {
2761        self.upload
2762    }
2763
2764    /// Returns whether this update grew and replaced the mesh GPU buffer.
2765    pub fn reallocated(self) -> bool {
2766        self.reallocated
2767    }
2768}
2769
2770/// Counts associated with one particle-field update or draw.
2771#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2772pub struct ParticleStatistics {
2773    submitted: usize,
2774    visibility_checked: usize,
2775    visible: usize,
2776    culled: usize,
2777    budget_limited: usize,
2778    dropped: usize,
2779    rendered: usize,
2780}
2781
2782impl ParticleStatistics {
2783    /// Returns instances supplied by the host.
2784    pub fn submitted(self) -> usize {
2785        self.submitted
2786    }
2787
2788    /// Returns instances tested against the camera viewport this frame.
2789    pub fn visibility_checked(self) -> usize {
2790        self.visibility_checked
2791    }
2792
2793    /// Returns checked instances that intersect the camera viewport.
2794    pub fn visible(self) -> usize {
2795        self.visible
2796    }
2797
2798    /// Returns instances outside the current camera viewport.
2799    pub fn culled(self) -> usize {
2800        self.culled
2801    }
2802
2803    /// Returns unchecked or camera-visible instances omitted by the render budget.
2804    pub fn budget_limited(self) -> usize {
2805        self.budget_limited
2806    }
2807
2808    /// Returns instances rejected before GPU submission.
2809    pub fn dropped(self) -> usize {
2810        self.dropped
2811    }
2812
2813    /// Returns instances submitted to the particle draw call.
2814    pub fn rendered(self) -> usize {
2815        self.rendered
2816    }
2817}
2818
2819/// Hard steady-state per-field limits for bounding particle visualization.
2820///
2821/// Atomic replacement temporarily retains the old and fully prepared new
2822/// state together. Its CPU/GPU peak is therefore bounded by the sum of the old
2823/// and new budgets, while every committed field stays within its own budget.
2824#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2825pub struct ParticleRenderBudget {
2826    max_visible_instances: usize,
2827    max_retained_bytes: usize,
2828    max_gpu_bytes: usize,
2829    max_upload_bytes_per_frame: usize,
2830    max_visibility_checks_per_frame: usize,
2831}
2832
2833impl ParticleRenderBudget {
2834    /// Bytes used by one retained or visibility-staging particle slot.
2835    pub const INSTANCE_BYTES: usize = std::mem::size_of::<ParticleGpu>();
2836
2837    /// No application-level cap beyond active-device allocation limits.
2838    pub const UNBOUNDED: Self = Self {
2839        max_visible_instances: usize::MAX,
2840        max_retained_bytes: usize::MAX,
2841        max_gpu_bytes: usize::MAX,
2842        max_upload_bytes_per_frame: usize::MAX,
2843        max_visibility_checks_per_frame: usize::MAX,
2844    };
2845
2846    /// Creates explicit visible-instance, retained-CPU, GPU-memory, and
2847    /// per-frame upload caps.
2848    pub fn new(
2849        max_visible_instances: usize,
2850        max_retained_bytes: usize,
2851        max_gpu_bytes: usize,
2852        max_upload_bytes_per_frame: usize,
2853    ) -> Result<Self, ParticleBudgetError> {
2854        let minimum_bytes = Self::INSTANCE_BYTES;
2855        let minimum_retained_bytes = minimum_bytes.saturating_mul(2);
2856        if max_visible_instances == 0
2857            || max_visible_instances > u32::MAX as usize
2858            || max_retained_bytes < minimum_retained_bytes
2859            || max_gpu_bytes < minimum_bytes
2860            || max_upload_bytes_per_frame < minimum_bytes
2861        {
2862            return Err(ParticleBudgetError::InvalidLimit);
2863        }
2864        Ok(Self {
2865            max_visible_instances,
2866            max_retained_bytes,
2867            max_gpu_bytes,
2868            max_upload_bytes_per_frame,
2869            max_visibility_checks_per_frame: usize::MAX,
2870        })
2871    }
2872
2873    /// Caps camera visibility checks while sampling candidates uniformly across
2874    /// the retained field. The cap must fit the effective visible-instance cap.
2875    pub fn with_max_visibility_checks(
2876        mut self,
2877        max_visibility_checks_per_frame: usize,
2878    ) -> Result<Self, ParticleBudgetError> {
2879        if max_visibility_checks_per_frame < self.instance_limit() {
2880            return Err(ParticleBudgetError::InvalidLimit);
2881        }
2882        self.max_visibility_checks_per_frame = max_visibility_checks_per_frame;
2883        Ok(self)
2884    }
2885
2886    /// Returns the maximum camera-visible instances considered for drawing.
2887    pub const fn max_visible_instances(self) -> usize {
2888        self.max_visible_instances
2889    }
2890
2891    /// Returns the maximum steady-state engine-owned particle allocation in bytes.
2892    pub const fn max_retained_bytes(self) -> usize {
2893        self.max_retained_bytes
2894    }
2895
2896    /// Returns the maximum particle instance-buffer allocation in bytes.
2897    pub const fn max_gpu_bytes(self) -> usize {
2898        self.max_gpu_bytes
2899    }
2900
2901    /// Returns the maximum particle bytes uploaded by one render call.
2902    pub const fn max_upload_bytes_per_frame(self) -> usize {
2903        self.max_upload_bytes_per_frame
2904    }
2905
2906    /// Returns the maximum retained instances checked against the viewport.
2907    pub const fn max_visibility_checks_per_frame(self) -> usize {
2908        self.max_visibility_checks_per_frame
2909    }
2910
2911    fn instance_limit(self) -> usize {
2912        self.max_visible_instances
2913            .min(self.max_gpu_bytes / std::mem::size_of::<ParticleGpu>())
2914            .min(self.max_upload_bytes_per_frame / std::mem::size_of::<ParticleGpu>())
2915    }
2916}
2917
2918impl Default for ParticleRenderBudget {
2919    fn default() -> Self {
2920        Self::UNBOUNDED
2921    }
2922}
2923
2924/// Invalid particle visualization resource budget.
2925#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2926pub enum ParticleBudgetError {
2927    /// CPU retention must fit one source plus one staging slot; GPU/upload
2928    /// limits must each fit at least one visible particle instance.
2929    InvalidLimit,
2930}
2931
2932impl fmt::Display for ParticleBudgetError {
2933    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2934        write!(
2935            formatter,
2936            "particle budget must fit one retained instance, its visibility staging slot, and one visible GPU upload"
2937        )
2938    }
2939}
2940
2941impl Error for ParticleBudgetError {}
2942
2943/// Renderer-owned instanced particles for high-volume simulation visuals.
2944///
2945/// The field retains its validated CPU instances so it can be recreated after
2946/// device loss. Its GPU instance buffer grows only when a replacement exceeds
2947/// the current capacity.
2948pub struct ParticleField2d {
2949    renderer_identity: Arc<()>,
2950    instance_buffer: Arc<wgpu::Buffer>,
2951    instances: Vec<ParticleGpu>,
2952    visible_instances: Vec<ParticleGpu>,
2953    instance_capacity: usize,
2954    budget: ParticleRenderBudget,
2955    statistics: ParticleStatistics,
2956}
2957
2958impl ParticleField2d {
2959    /// Returns the number of particle instances currently stored.
2960    pub fn instance_count(&self) -> usize {
2961        self.instances.len()
2962    }
2963
2964    /// Returns the number of instances that fit without reallocating GPU memory.
2965    pub fn instance_capacity(&self) -> usize {
2966        self.instance_capacity
2967    }
2968
2969    /// Returns the most recent update or draw counts.
2970    pub fn statistics(&self) -> ParticleStatistics {
2971        self.statistics
2972    }
2973
2974    /// Returns the hard visualization budget applied by rendering.
2975    pub fn budget(&self) -> ParticleRenderBudget {
2976        self.budget
2977    }
2978
2979    /// Returns retained CPU memory used for recovery and validation.
2980    pub fn recovery_memory_bytes(&self) -> usize {
2981        self.instances
2982            .capacity()
2983            .saturating_mul(std::mem::size_of::<ParticleGpu>())
2984    }
2985
2986    /// Returns currently reserved CPU bytes for retained and culled instance lists.
2987    pub fn cpu_allocation_bytes(&self) -> usize {
2988        self.instances
2989            .capacity()
2990            .saturating_add(self.visible_instances.capacity())
2991            .saturating_mul(std::mem::size_of::<ParticleGpu>())
2992    }
2993
2994    /// Returns allocated GPU instance-buffer bytes.
2995    pub fn gpu_allocation_bytes(&self) -> usize {
2996        self.instance_capacity
2997            .saturating_mul(std::mem::size_of::<ParticleGpu>())
2998    }
2999}
3000
3001/// Failure while creating or updating a [`ParticleField2d`].
3002#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3003pub enum ParticleFieldError {
3004    /// An input instance violates the portable particle contract.
3005    InvalidInstance,
3006    /// A partial update lies outside the field's current instance range.
3007    UpdateRangeOutOfBounds,
3008    /// The field belongs to another renderer and GPU device.
3009    RendererMismatch,
3010    /// The instance capacity exceeds the current device's buffer limit.
3011    CapacityTooLarge,
3012    /// The retained CPU allocation exceeds the host-selected hard ceiling.
3013    RetainedBudgetExceeded {
3014        /// Configured retained-allocation ceiling.
3015        limit: usize,
3016        /// Required or actually reserved retained bytes.
3017        actual: usize,
3018    },
3019    /// Particle retention, replacement, or visibility-staging storage could
3020    /// not be reserved without panicking.
3021    AllocationFailed {
3022        /// Bytes requested by the failed particle-storage reservation.
3023        requested_bytes: usize,
3024    },
3025}
3026
3027impl fmt::Display for ParticleFieldError {
3028    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3029        match self {
3030            Self::InvalidInstance => write!(
3031                formatter,
3032                "particle field positions, depth, and radius must be portable and colors valid"
3033            ),
3034            Self::UpdateRangeOutOfBounds => {
3035                write!(
3036                    formatter,
3037                    "particle update range is outside the current field"
3038                )
3039            }
3040            Self::RendererMismatch => {
3041                write!(formatter, "particle field belongs to a different renderer")
3042            }
3043            Self::CapacityTooLarge => {
3044                write!(
3045                    formatter,
3046                    "particle field exceeds the GPU instance-buffer limit"
3047                )
3048            }
3049            Self::RetainedBudgetExceeded { limit, actual } => write!(
3050                formatter,
3051                "particle retained CPU allocation {actual} bytes exceeds limit {limit}"
3052            ),
3053            Self::AllocationFailed { requested_bytes } => write!(
3054                formatter,
3055                "could not reserve {requested_bytes} bytes for particle storage"
3056            ),
3057        }
3058    }
3059}
3060
3061impl Error for ParticleFieldError {}
3062
3063/// CPU-side outcome of one particle-field update.
3064#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3065pub struct ParticleFieldUpdateReport {
3066    statistics: ParticleStatistics,
3067    preparation: Duration,
3068    reallocated: bool,
3069}
3070
3071impl ParticleFieldUpdateReport {
3072    /// Returns submitted, visible, dropped, and rendered instance counts.
3073    pub fn statistics(self) -> ParticleStatistics {
3074        self.statistics
3075    }
3076
3077    /// Returns CPU time spent validating and retaining the new visual state.
3078    ///
3079    /// GPU upload is deferred until rendering, after camera culling has selected
3080    /// the compact visible set.
3081    pub fn preparation(self) -> Duration {
3082        self.preparation
3083    }
3084
3085    /// Backward-compatible alias for [`ParticleFieldUpdateReport::preparation`].
3086    #[deprecated(note = "particle GPU upload is deferred to render; use preparation()")]
3087    pub fn upload(self) -> Duration {
3088        self.preparation
3089    }
3090
3091    /// Returns whether this update grew and replaced the GPU instance buffer.
3092    pub fn reallocated(self) -> bool {
3093        self.reallocated
3094    }
3095}
3096
3097/// Failure while rendering a [`ParticleField2d`].
3098#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3099pub enum ParticleFieldRenderError {
3100    /// The field belongs to another renderer and GPU device.
3101    RendererMismatch,
3102    /// The clear color is not normalized linear RGBA.
3103    InvalidBackground,
3104    /// Particle projection cannot be proven inside the portable GPU envelope.
3105    InvalidGeometryTransform,
3106    /// Surface acquisition or presentation failed.
3107    Frame(RendererFrameError),
3108}
3109
3110impl fmt::Display for ParticleFieldRenderError {
3111    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3112        match self {
3113            Self::RendererMismatch => {
3114                write!(formatter, "particle field belongs to a different renderer")
3115            }
3116            Self::InvalidBackground => {
3117                write!(formatter, "particle field background must be normalized")
3118            }
3119            Self::InvalidGeometryTransform => {
3120                write!(formatter, "particle field geometry transform is invalid")
3121            }
3122            Self::Frame(error) => write!(formatter, "particle field frame failed: {error}"),
3123        }
3124    }
3125}
3126
3127impl Error for ParticleFieldRenderError {}
3128
3129/// Renderer-owned scalar texture retaining its validated source field.
3130pub struct ScalarFieldTexture {
3131    renderer_identity: Arc<()>,
3132    texture: wgpu::Texture,
3133    field: ScalarField,
3134    source_minimum: f32,
3135    source_maximum: f32,
3136}
3137
3138impl ScalarFieldTexture {
3139    /// Returns the current grid width in texels.
3140    pub fn width(&self) -> usize {
3141        self.field.width()
3142    }
3143
3144    /// Returns the current grid height in texels.
3145    pub fn height(&self) -> usize {
3146        self.field.height()
3147    }
3148
3149    /// Returns retained CPU scalar data used for recovery and uploads.
3150    pub fn field(&self) -> &ScalarField {
3151        &self.field
3152    }
3153
3154    /// Returns retained CPU scalar bytes used for device-loss recovery.
3155    pub fn recovery_memory_bytes(&self) -> usize {
3156        self.field.value_allocation_bytes()
3157    }
3158
3159    /// Returns nominal `R32Float` texel-storage bytes requested from the GPU,
3160    /// excluding backend row/tile/page alignment and metadata.
3161    pub fn gpu_allocation_bytes(&self) -> usize {
3162        self.field
3163            .values()
3164            .len()
3165            .saturating_mul(std::mem::size_of::<f32>())
3166    }
3167}
3168
3169/// A renderer-owned offscreen color target in physical texture pixels.
3170///
3171/// Targets preserve GPU pixels only; a host must redraw them after device
3172/// recreation. Use the renderer's physical [`WgpuRenderer::size`] when a
3173/// target should match the presentation surface exactly.
3174pub struct RenderTarget2d {
3175    renderer_identity: Arc<()>,
3176    resource_identity: Arc<()>,
3177    _texture: wgpu::Texture,
3178    view: wgpu::TextureView,
3179    width: u32,
3180    height: u32,
3181    allocation_bytes: usize,
3182}
3183
3184/// A pair of offscreen targets used for bounded temporal accumulation.
3185///
3186/// Each accumulation retains a caller-selected amount of the previous frame
3187/// and then composites a distinct source target over it. The buffer owns no
3188/// domain state and can therefore serve particles, scalar fields, or any later
3189/// target-rendering producer.
3190pub struct TrailBuffer2d {
3191    renderer_identity: Arc<()>,
3192    front: RenderTarget2d,
3193    back: RenderTarget2d,
3194}
3195
3196impl TrailBuffer2d {
3197    /// Returns trail-buffer width in physical texture pixels.
3198    pub fn width(&self) -> u32 {
3199        self.front.width()
3200    }
3201
3202    /// Returns trail-buffer height in physical texture pixels.
3203    pub fn height(&self) -> u32 {
3204        self.front.height()
3205    }
3206
3207    /// Returns trail-buffer physical dimensions.
3208    pub fn size(&self) -> (u32, u32) {
3209        self.front.size()
3210    }
3211
3212    /// Returns nominal texel-storage bytes for both ping-pong textures.
3213    pub fn allocation_bytes(&self) -> usize {
3214        self.front
3215            .allocation_bytes()
3216            .saturating_add(self.back.allocation_bytes())
3217    }
3218}
3219
3220impl RenderTarget2d {
3221    /// Returns target width in physical texture pixels.
3222    pub fn width(&self) -> u32 {
3223        self.width
3224    }
3225
3226    /// Returns target height in physical texture pixels.
3227    pub fn height(&self) -> u32 {
3228        self.height
3229    }
3230
3231    /// Returns the physical texture dimensions.
3232    pub fn size(&self) -> (u32, u32) {
3233        (self.width, self.height)
3234    }
3235
3236    /// Returns nominal single-level texel-storage bytes implied by its format.
3237    /// Backend row/tile/page alignment and resource metadata are not observable
3238    /// through wgpu and are therefore excluded.
3239    pub fn allocation_bytes(&self) -> usize {
3240        self.allocation_bytes
3241    }
3242}
3243
3244/// Failure while creating or composing a [`RenderTarget2d`].
3245#[derive(Debug, Clone, Copy, PartialEq)]
3246pub enum RenderTargetError {
3247    /// Target dimensions must both be non-zero.
3248    ZeroDimension,
3249    /// Dimensions exceed the current device's supported target size or allocation range.
3250    DimensionsTooLarge,
3251    /// The target belongs to another renderer and GPU device.
3252    RendererMismatch,
3253    /// Opacity must be finite and within `0.0..=1.0`.
3254    InvalidOpacity,
3255    /// A temporal source must not be one of its destination ping-pong targets.
3256    SourceAliasesDestination,
3257    /// The destination clear color was not normalized linear RGBA.
3258    InvalidBackground,
3259    /// Surface acquisition or presentation failed.
3260    Frame(RendererFrameError),
3261}
3262
3263impl fmt::Display for RenderTargetError {
3264    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3265        match self {
3266            Self::ZeroDimension => write!(formatter, "render target dimensions must be non-zero"),
3267            Self::DimensionsTooLarge => {
3268                write!(formatter, "render target dimensions exceed device limits")
3269            }
3270            Self::RendererMismatch => {
3271                write!(formatter, "render target belongs to a different renderer")
3272            }
3273            Self::InvalidOpacity => write!(
3274                formatter,
3275                "render target opacity must be finite and in 0.0..=1.0"
3276            ),
3277            Self::SourceAliasesDestination => {
3278                write!(
3279                    formatter,
3280                    "trail source must be distinct from its destination targets"
3281                )
3282            }
3283            Self::InvalidBackground => {
3284                write!(formatter, "render target background must be normalized")
3285            }
3286            Self::Frame(error) => write!(formatter, "render target frame failed: {error}"),
3287        }
3288    }
3289}
3290
3291impl Error for RenderTargetError {}
3292
3293/// Failure while creating or updating a [`ScalarFieldTexture`].
3294#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3295pub enum ScalarFieldTextureError {
3296    /// The texture belongs to another renderer and GPU device.
3297    RendererMismatch,
3298    /// Grid dimensions exceed the addressable `wgpu` texture range.
3299    DimensionsTooLarge,
3300    /// A region does not fit inside the current scalar texture.
3301    UpdateRegionOutOfBounds,
3302    /// Region values did not match the region dimensions.
3303    InvalidUpdateValueCount,
3304    /// A region value was NaN or infinite.
3305    NonFiniteUpdateValue,
3306    /// A finite scalar source lies outside the portable GPU arithmetic envelope.
3307    NonPortableValue,
3308    /// CPU recovery storage could not be reserved.
3309    AllocationFailed {
3310        /// Bytes requested for the rejected retained scalar copy.
3311        requested_bytes: usize,
3312    },
3313}
3314
3315impl fmt::Display for ScalarFieldTextureError {
3316    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3317        match self {
3318            Self::RendererMismatch => write!(
3319                formatter,
3320                "scalar field texture belongs to a different renderer"
3321            ),
3322            Self::DimensionsTooLarge => write!(
3323                formatter,
3324                "scalar field dimensions exceed GPU texture limits"
3325            ),
3326            Self::UpdateRegionOutOfBounds => {
3327                write!(formatter, "scalar texture update region is out of bounds")
3328            }
3329            Self::InvalidUpdateValueCount => {
3330                write!(
3331                    formatter,
3332                    "scalar texture update values do not match the region"
3333                )
3334            }
3335            Self::NonFiniteUpdateValue => {
3336                write!(formatter, "scalar texture update values must be finite")
3337            }
3338            Self::NonPortableValue => write!(
3339                formatter,
3340                "scalar values must be normal-or-zero and remain inside the portable GPU arithmetic envelope"
3341            ),
3342            Self::AllocationFailed { requested_bytes } => write!(
3343                formatter,
3344                "could not reserve {requested_bytes} bytes for scalar field recovery data"
3345            ),
3346        }
3347    }
3348}
3349
3350impl Error for ScalarFieldTextureError {}
3351
3352/// Failure while rendering a scalar texture as a heatmap.
3353#[derive(Debug, Clone, Copy, PartialEq)]
3354pub enum ScalarFieldRenderError {
3355    /// The texture belongs to another renderer and GPU device.
3356    RendererMismatch,
3357    /// The scalar range was non-finite or did not have positive extent.
3358    InvalidValueRange {
3359        /// Lower bound supplied by the caller.
3360        minimum: f32,
3361        /// Upper bound supplied by the caller.
3362        maximum: f32,
3363    },
3364    /// The clear color is not normalized linear RGBA.
3365    InvalidBackground,
3366    /// Surface acquisition or presentation failed.
3367    Frame(RendererFrameError),
3368}
3369
3370impl fmt::Display for ScalarFieldRenderError {
3371    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3372        match self {
3373            Self::RendererMismatch => write!(
3374                formatter,
3375                "scalar field texture belongs to a different renderer"
3376            ),
3377            Self::InvalidValueRange { minimum, maximum } => {
3378                write!(formatter, "invalid scalar value range {minimum}..{maximum}")
3379            }
3380            Self::InvalidBackground => {
3381                write!(formatter, "scalar field background must be normalized")
3382            }
3383            Self::Frame(error) => write!(formatter, "scalar field frame failed: {error}"),
3384        }
3385    }
3386}
3387
3388impl Error for ScalarFieldRenderError {}
3389
3390/// CPU-side outcome of one scalar-field texture upload.
3391#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3392pub struct ScalarFieldUploadReport {
3393    upload: Duration,
3394    reallocated: bool,
3395}
3396
3397impl ScalarFieldUploadReport {
3398    /// Returns CPU time spent allocating when needed and enqueuing the upload.
3399    pub fn upload(self) -> Duration {
3400        self.upload
3401    }
3402
3403    /// Returns whether differing dimensions recreated the GPU texture.
3404    pub fn reallocated(self) -> bool {
3405        self.reallocated
3406    }
3407}
3408
3409/// Failure while rendering a [`DynamicMesh2d`].
3410#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3411pub enum DynamicMeshRenderError {
3412    /// The mesh belongs to another renderer and GPU device.
3413    RendererMismatch,
3414    /// The clear color is not normalized linear RGBA.
3415    InvalidBackground,
3416    /// Frame rendering failed after dynamic-mesh ownership validation.
3417    Frame(RendererFrameError),
3418}
3419
3420impl fmt::Display for DynamicMeshRenderError {
3421    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
3422        match self {
3423            Self::RendererMismatch => {
3424                write!(formatter, "dynamic mesh belongs to a different renderer")
3425            }
3426            Self::InvalidBackground => {
3427                write!(formatter, "dynamic mesh background must be normalized")
3428            }
3429            Self::Frame(error) => write!(formatter, "dynamic mesh frame failed: {error}"),
3430        }
3431    }
3432}
3433
3434impl Error for DynamicMeshRenderError {}
3435
3436impl PreparedScene {
3437    /// Returns the number of accepted source scene commands.
3438    pub fn command_count(&self) -> usize {
3439        self.command_count
3440    }
3441
3442    /// Returns the number of triangle-list vertices stored in the GPU buffer.
3443    pub fn vertex_count(&self) -> usize {
3444        self.vertex_count
3445    }
3446
3447    /// Returns the number of clip-compatible draw batches.
3448    pub fn draw_batch_count(&self) -> usize {
3449        self.draw_batches.len()
3450    }
3451
3452    /// Returns currently allocated CPU recovery bytes for vertices and draw batches.
3453    pub fn recovery_memory_bytes(&self) -> usize {
3454        self.vertices
3455            .capacity()
3456            .saturating_mul(std::mem::size_of::<Vertex>())
3457            .saturating_add(
3458                self.draw_batches
3459                    .capacity()
3460                    .saturating_mul(std::mem::size_of::<PreparedDrawBatch>()),
3461            )
3462    }
3463
3464    /// Returns command-level tessellation results captured during preparation.
3465    pub fn tessellation_stats(&self) -> TessellationStats {
3466        self.tessellation
3467    }
3468}
3469
3470impl PreparedScreenScene {
3471    /// Returns the number of accepted source screen commands.
3472    pub fn command_count(&self) -> usize {
3473        self.scene.command_count()
3474    }
3475
3476    /// Returns the retained triangle-list vertex count.
3477    pub fn vertex_count(&self) -> usize {
3478        self.scene.vertex_count()
3479    }
3480
3481    /// Returns the number of clip-compatible draw batches.
3482    pub fn draw_batch_count(&self) -> usize {
3483        self.scene.draw_batch_count()
3484    }
3485
3486    /// Returns retained CPU bytes available for device-loss recovery.
3487    pub fn recovery_memory_bytes(&self) -> usize {
3488        self.scene.recovery_memory_bytes()
3489    }
3490
3491    /// Returns preparation-time tessellation statistics.
3492    pub fn tessellation_stats(&self) -> TessellationStats {
3493        self.scene.tessellation_stats()
3494    }
3495}
3496
3497/// `wgpu` backend that renders [`Scene`] commands into a presentation surface.
3498///
3499/// The renderer owns the GPU device, queue, surface, pipeline, and transient
3500/// vertex buffer. Window creation stays outside the library so each application
3501/// can choose its own windowing framework.
3502pub struct WgpuRenderer {
3503    renderer_identity: Arc<()>,
3504    _instance: wgpu::Instance,
3505    surface: wgpu::Surface<'static>,
3506    _adapter: wgpu::Adapter,
3507    adapter_info: wgpu::AdapterInfo,
3508    device: wgpu::Device,
3509    queue: wgpu::Queue,
3510    config: wgpu::SurfaceConfiguration,
3511    requested_present_mode: RendererPresentMode,
3512    surface_present_mode: RendererSurfacePresentMode,
3513    pre_present_notify: Option<Arc<dyn Fn() + Send + Sync>>,
3514    scale_factor: f64,
3515    pipeline: wgpu::RenderPipeline,
3516    target_pipeline: wgpu::RenderPipeline,
3517    dynamic_pipeline: wgpu::RenderPipeline,
3518    particle_pipeline: wgpu::RenderPipeline,
3519    target_particle_pipeline: wgpu::RenderPipeline,
3520    heatmap_pipeline: wgpu::RenderPipeline,
3521    target_heatmap_pipeline: wgpu::RenderPipeline,
3522    composition_pipelines: CompositionPipelines,
3523    target_composition_pipelines: CompositionPipelines,
3524    image_renderer: ImageRenderer,
3525    mesh3d_renderer: Mesh3dRenderer,
3526    camera_uniform_buffer: wgpu::Buffer,
3527    camera_bind_group: wgpu::BindGroup,
3528    camera_bind_group_layout: wgpu::BindGroupLayout,
3529    heatmap_uniform_buffer: wgpu::Buffer,
3530    heatmap_bind_group_layout: wgpu::BindGroupLayout,
3531    color_map_cache: Option<CachedColorMap>,
3532    vertex_buffer: Arc<wgpu::Buffer>,
3533    particle_unit_buffer: wgpu::Buffer,
3534    vertex_capacity: usize,
3535    multisample_target: Option<MultisampleTarget>,
3536    sample_count: u32,
3537    vertices: Vec<Vertex>,
3538    draw_batches: Vec<PreparedDrawBatch>,
3539    retired_devices: Vec<RetiredDevice>,
3540    max_quarantined_devices: usize,
3541}
3542
3543struct RetiredDevice {
3544    _adapter: wgpu::Adapter,
3545    _device: wgpu::Device,
3546    _queue: wgpu::Queue,
3547}
3548
3549impl WgpuRenderer {
3550    /// Creates a renderer for a window or canvas surface target.
3551    ///
3552    /// `width` and `height` are physical surface pixels. Zero sizes are clamped
3553    /// to one pixel because `wgpu` surfaces cannot be configured at zero size.
3554    /// This convenience constructor assumes a display scale factor of `1.0`;
3555    /// HiDPI hosts should use [`WgpuRenderer::new_with_options`].
3556    pub async fn new(
3557        surface_target: impl Into<wgpu::SurfaceTarget<'static>>,
3558        width: u32,
3559        height: u32,
3560    ) -> Result<Self, RendererInitError> {
3561        Self::new_with_options(
3562            surface_target,
3563            width,
3564            height,
3565            WgpuRendererOptions::default(),
3566        )
3567        .await
3568    }
3569
3570    /// Creates a renderer with explicit options.
3571    ///
3572    /// Use this when measuring renderer throughput or when the host application
3573    /// needs control over presentation behavior or display scale.
3574    pub async fn new_with_options(
3575        surface_target: impl Into<wgpu::SurfaceTarget<'static>>,
3576        width: u32,
3577        height: u32,
3578        options: WgpuRendererOptions,
3579    ) -> Result<Self, RendererInitError> {
3580        let instance =
3581            wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
3582        let surface = instance
3583            .create_surface(surface_target)
3584            .map_err(RendererInitError::CreateSurface)?;
3585        let adapter = instance
3586            .request_adapter(&wgpu::RequestAdapterOptions {
3587                power_preference: wgpu::PowerPreference::HighPerformance,
3588                force_fallback_adapter: false,
3589                compatible_surface: Some(&surface),
3590                apply_limit_buckets: false,
3591            })
3592            .await
3593            .map_err(RendererInitError::RequestAdapter)?;
3594        let adapter_info = adapter.get_info();
3595
3596        let (device, queue) = adapter
3597            .request_device(&wgpu::DeviceDescriptor {
3598                label: Some("sim-engine device"),
3599                required_features: wgpu::Features::empty(),
3600                required_limits: wgpu::Limits::default(),
3601                experimental_features: wgpu::ExperimentalFeatures::disabled(),
3602                memory_hints: wgpu::MemoryHints::Performance,
3603                trace: wgpu::Trace::Off,
3604            })
3605            .await
3606            .map_err(RendererInitError::RequestDevice)?;
3607
3608        let width = width.max(1);
3609        let height = height.max(1);
3610        let dimension_limit = device.limits().max_texture_dimension_2d;
3611        if width > dimension_limit || height > dimension_limit {
3612            return Err(RendererInitError::SurfaceDimensionsTooLarge {
3613                width,
3614                height,
3615                limit: dimension_limit,
3616            });
3617        }
3618        let surface_capabilities = surface.get_capabilities(&adapter);
3619        let mut config = surface
3620            .get_default_config(&adapter, width, height)
3621            .ok_or(RendererInitError::NoSurfaceConfig)?;
3622        let surface_present_mode = select_surface_present_mode(
3623            options.present_mode(),
3624            &surface_capabilities.present_modes,
3625        );
3626        config.present_mode = surface_present_mode.to_wgpu();
3627        surface.configure(&device, &config);
3628
3629        let sample_count = preferred_sample_count(&adapter, config.format);
3630        let PipelineResources {
3631            pipeline,
3632            target_pipeline,
3633            dynamic_pipeline,
3634            particle_pipeline,
3635            target_particle_pipeline,
3636            heatmap_pipeline,
3637            target_heatmap_pipeline,
3638            composition_pipelines,
3639            target_composition_pipelines,
3640            camera_uniform_buffer,
3641            camera_bind_group,
3642            camera_bind_group_layout,
3643            heatmap_uniform_buffer,
3644            heatmap_bind_group_layout,
3645        } = create_pipeline(&device, config.format, sample_count);
3646        let vertex_buffer = Arc::new(create_vertex_buffer(&device, INITIAL_VERTEX_CAPACITY));
3647        let particle_unit_buffer = create_submitted_particle_unit_buffer(&device, &queue);
3648        let multisample_target = create_multisample_target(&device, &config, sample_count);
3649        let image_renderer = ImageRenderer::new(&device, config.format, sample_count);
3650        let mesh3d_renderer = Mesh3dRenderer::new(&device, config.format);
3651
3652        Ok(Self {
3653            renderer_identity: Arc::new(()),
3654            _instance: instance,
3655            surface,
3656            _adapter: adapter,
3657            adapter_info,
3658            device,
3659            queue,
3660            config,
3661            requested_present_mode: options.present_mode(),
3662            surface_present_mode,
3663            pre_present_notify: None,
3664            scale_factor: options.scale_factor(),
3665            pipeline,
3666            target_pipeline,
3667            dynamic_pipeline,
3668            particle_pipeline,
3669            target_particle_pipeline,
3670            heatmap_pipeline,
3671            target_heatmap_pipeline,
3672            composition_pipelines,
3673            target_composition_pipelines,
3674            image_renderer,
3675            mesh3d_renderer,
3676            camera_uniform_buffer,
3677            camera_bind_group,
3678            camera_bind_group_layout,
3679            heatmap_uniform_buffer,
3680            heatmap_bind_group_layout,
3681            color_map_cache: None,
3682            vertex_buffer,
3683            particle_unit_buffer,
3684            vertex_capacity: INITIAL_VERTEX_CAPACITY,
3685            multisample_target,
3686            sample_count,
3687            vertices: Vec::new(),
3688            draw_batches: Vec::new(),
3689            retired_devices: Vec::new(),
3690            max_quarantined_devices: options.max_quarantined_devices(),
3691        })
3692    }
3693
3694    /// Returns the configured surface size in physical pixels.
3695    pub fn size(&self) -> (u32, u32) {
3696        (self.config.width, self.config.height)
3697    }
3698
3699    /// Returns the render viewport size in logical screen pixels.
3700    ///
3701    /// Scene clipping, stroke widths, shadows, and camera zoom use this logical
3702    /// coordinate space so their visual size remains stable across display DPI.
3703    pub fn logical_size(&self) -> (f32, f32) {
3704        let scale_factor = self.scale_factor as f32;
3705        (
3706            self.config.width as f32 / scale_factor,
3707            self.config.height as f32 / scale_factor,
3708        )
3709    }
3710
3711    /// Returns the current camera viewport in logical screen pixels.
3712    pub fn logical_viewport(&self) -> Result<LogicalViewport, crate::LogicalViewportError> {
3713        let (width, height) = self.logical_size();
3714        LogicalViewport::new(width, height)
3715    }
3716
3717    /// Converts a physical surface position into logical screen pixels.
3718    pub fn physical_to_logical_screen(
3719        &self,
3720        position: PhysicalScreenPosition,
3721    ) -> Result<LogicalScreenPosition, RendererCoordinateError> {
3722        physical_to_logical_screen(position, self.scale_factor as f32)
3723    }
3724
3725    /// Converts a logical screen position into physical surface pixels.
3726    pub fn logical_to_physical_screen(
3727        &self,
3728        position: LogicalScreenPosition,
3729    ) -> Result<PhysicalScreenPosition, RendererCoordinateError> {
3730        logical_to_physical_screen(position, self.scale_factor as f32)
3731    }
3732
3733    /// Returns physical surface pixels per logical screen pixel.
3734    pub fn scale_factor(&self) -> f64 {
3735        self.scale_factor
3736    }
3737
3738    /// Returns the concrete presentation mode selected for the active surface.
3739    ///
3740    /// `RendererPresentMode::NoVsync` prefers Immediate, then Mailbox, then
3741    /// FIFO. This method reveals which supported fallback was configured. The
3742    /// desktop compositor may still pace host redraw callbacks independently.
3743    pub fn surface_present_mode(&self) -> RendererSurfacePresentMode {
3744        self.surface_present_mode
3745    }
3746
3747    /// Installs a host callback invoked immediately before synchronized
3748    /// surface presentation.
3749    ///
3750    /// A winit host should capture its `Arc<Window>` and call
3751    /// `Window::pre_present_notify` from this callback. The renderer invokes
3752    /// it after command submission and immediately before `Queue::present`,
3753    /// but only when the concrete surface mode is Mailbox, FIFO, or
3754    /// FIFO-relaxed. Immediate presentation deliberately remains uncapped.
3755    pub fn set_pre_present_notify(&mut self, notify: impl Fn() + Send + Sync + 'static) {
3756        self.pre_present_notify = Some(Arc::new(notify));
3757    }
3758
3759    /// Removes the synchronized-presentation callback, if one is installed.
3760    pub fn clear_pre_present_notify(&mut self) {
3761        self.pre_present_notify = None;
3762    }
3763
3764    fn notify_before_present(&self) {
3765        invoke_pre_present_notify(
3766            self.surface_present_mode,
3767            self.pre_present_notify.as_deref(),
3768        );
3769    }
3770
3771    /// Returns the active graphics adapter's human-readable name.
3772    pub fn adapter_name(&self) -> &str {
3773        &self.adapter_info.name
3774    }
3775
3776    /// Returns the active graphics API backend as a stable lowercase name.
3777    pub fn adapter_backend(&self) -> &'static str {
3778        self.adapter_info.backend.to_str()
3779    }
3780
3781    /// Returns the PCI vendor identifier reported for the active adapter.
3782    pub fn adapter_vendor_id(&self) -> u32 {
3783        self.adapter_info.vendor
3784    }
3785
3786    /// Returns the device identifier reported for the active adapter.
3787    pub fn adapter_device_id(&self) -> u32 {
3788        self.adapter_info.device
3789    }
3790
3791    /// Returns the backend-reported PCI bus address for the active adapter.
3792    ///
3793    /// Vulkan adapters expose this as `domain:bus:device.function` when the
3794    /// driver supports `VK_EXT_pci_bus_info`. An empty string means that the
3795    /// backend cannot identify a physical adapter instance; release evidence
3796    /// must not treat model identifiers alone as instance identity.
3797    pub fn adapter_pci_bus_id(&self) -> &str {
3798        &self.adapter_info.device_pci_bus_id
3799    }
3800
3801    /// Returns the texture format selected for the active presentation surface.
3802    pub fn surface_format(&self) -> wgpu::TextureFormat {
3803        self.config.format
3804    }
3805
3806    /// Returns the raster sample count selected for the active surface format.
3807    pub fn surface_sample_count(&self) -> u32 {
3808        self.sample_count
3809    }
3810
3811    /// Returns the driver name reported by the active graphics adapter.
3812    pub fn adapter_driver(&self) -> &str {
3813        &self.adapter_info.driver
3814    }
3815
3816    /// Returns the driver version or implementation detail reported by the adapter.
3817    pub fn adapter_driver_info(&self) -> &str {
3818        &self.adapter_info.driver_info
3819    }
3820
3821    /// Returns previous logical devices retained for safe native-driver teardown.
3822    pub fn quarantined_device_count(&self) -> usize {
3823        self.retired_devices.len()
3824    }
3825
3826    /// Returns the configured maximum previous-device quarantine size.
3827    pub fn max_quarantined_device_count(&self) -> usize {
3828        self.max_quarantined_devices
3829    }
3830
3831    /// Returns successful recoveries available before the bounded quarantine is full.
3832    pub fn remaining_device_recoveries(&self) -> usize {
3833        self.max_quarantined_devices
3834            .saturating_sub(self.retired_devices.len())
3835    }
3836
3837    /// Blocks until all previously submitted GPU work has completed.
3838    ///
3839    /// This is intended for diagnostic throughput measurements, readback, and
3840    /// controlled resource teardown. Calling it in an interactive frame loop
3841    /// defeats normal CPU/GPU pipelining.
3842    pub fn wait_for_gpu_idle(&self) -> Result<(), wgpu::PollError> {
3843        self.device
3844            .poll(wgpu::PollType::wait_indefinitely())
3845            .map(|_| ())
3846    }
3847
3848    /// Replaces display scale without changing physical surface dimensions.
3849    ///
3850    /// Invalid values return an error and leave the current scale unchanged.
3851    pub fn set_scale_factor(
3852        &mut self,
3853        scale_factor: f64,
3854    ) -> Result<(), RendererConfigurationError> {
3855        validate_scale_factor(scale_factor)?;
3856        self.scale_factor = scale_factor;
3857        Ok(())
3858    }
3859
3860    /// Reconfigures the surface after a host window resize.
3861    ///
3862    /// Zero width or height is ignored because minimized windows often report
3863    /// zero size and `wgpu` cannot configure a zero-sized surface.
3864    pub fn resize(&mut self, width: u32, height: u32) -> Result<(), RendererConfigurationError> {
3865        if width == 0 || height == 0 {
3866            return Ok(());
3867        }
3868        validate_surface_dimensions(width, height, self.device.limits().max_texture_dimension_2d)?;
3869
3870        self.config.width = width;
3871        self.config.height = height;
3872        self.surface.configure(&self.device, &self.config);
3873        self.multisample_target =
3874            create_multisample_target(&self.device, &self.config, self.sample_count);
3875        Ok(())
3876    }
3877
3878    /// Reconfigures physical surface size and logical-to-physical display scale.
3879    ///
3880    /// Invalid scale returns an error without changing either value. Zero
3881    /// physical dimensions update the scale but leave the minimized surface
3882    /// configuration unchanged.
3883    pub fn resize_with_scale_factor(
3884        &mut self,
3885        width: u32,
3886        height: u32,
3887        scale_factor: f64,
3888    ) -> Result<(), RendererConfigurationError> {
3889        validate_scale_factor(scale_factor)?;
3890        if width != 0 && height != 0 {
3891            validate_surface_dimensions(
3892                width,
3893                height,
3894                self.device.limits().max_texture_dimension_2d,
3895            )?;
3896        }
3897        self.resize(width, height)?;
3898        self.scale_factor = scale_factor;
3899        Ok(())
3900    }
3901
3902    /// Draws a scene using the supplied camera.
3903    ///
3904    /// Scene positions and sizes are in world units unless a style explicitly
3905    /// says logical screen pixels. The renderer converts world coordinates to
3906    /// logical screen coordinates through [`Camera2d`], then to normalized device
3907    /// coordinates for `wgpu`. Scissor rectangles are converted to physical
3908    /// surface pixels at the final backend boundary.
3909    pub fn render(
3910        &mut self,
3911        scene: &Scene,
3912        camera: &Camera2d,
3913    ) -> Result<RenderStatus, RendererFrameError> {
3914        self.render_with_metrics(scene, camera)
3915            .map(RenderReport::status)
3916    }
3917
3918    /// Draws fixed logical-screen geometry independently of any world camera.
3919    pub fn render_screen_scene(
3920        &mut self,
3921        scene: &ScreenScene,
3922    ) -> Result<RenderStatus, RendererFrameError> {
3923        self.render_screen_scene_with_metrics(scene)
3924            .map(RenderReport::status)
3925    }
3926
3927    /// Draws fixed logical-screen geometry and returns CPU-side stage timings.
3928    pub fn render_screen_scene_with_metrics(
3929        &mut self,
3930        scene: &ScreenScene,
3931    ) -> Result<RenderReport, RendererFrameError> {
3932        let viewport = LogicalViewport::new(self.logical_size().0, self.logical_size().1)
3933            .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
3934        let camera =
3935            screen_camera(viewport).map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
3936        self.render_with_metrics(scene.as_scene(), &camera)
3937    }
3938
3939    /// Draws a scene and returns a CPU-side timing breakdown.
3940    ///
3941    /// Metrics separate tessellation, buffer upload, surface acquisition, and
3942    /// encode/submit/present dispatch. They do not measure GPU completion or the
3943    /// monitor scanout timestamp. Use this for diagnostics; [`WgpuRenderer::render`]
3944    /// is the simpler equivalent when stage timings are not needed.
3945    pub fn render_with_metrics(
3946        &mut self,
3947        scene: &Scene,
3948        camera: &Camera2d,
3949    ) -> Result<RenderReport, RendererFrameError> {
3950        self.render_with_metrics_in_region(scene, camera, None)
3951    }
3952
3953    /// Draws a world scene through a camera into one bounded logical viewport.
3954    ///
3955    /// Scene-local clips are interpreted relative to the viewport and are
3956    /// intersected with its physical bounds. The surface outside the viewport
3957    /// is cleared but receives no scene geometry.
3958    pub fn render_scene_in_viewport(
3959        &mut self,
3960        scene: &Scene,
3961        camera: &Camera2d,
3962        viewport: LogicalViewportRegion,
3963    ) -> Result<RenderStatus, RendererFrameError> {
3964        self.render_scene_in_viewport_with_metrics(scene, camera, viewport)
3965            .map(RenderReport::status)
3966    }
3967
3968    /// Draws one bounded scene viewport and returns CPU-side stage timings.
3969    pub fn render_scene_in_viewport_with_metrics(
3970        &mut self,
3971        scene: &Scene,
3972        camera: &Camera2d,
3973        viewport: LogicalViewportRegion,
3974    ) -> Result<RenderReport, RendererFrameError> {
3975        self.render_with_metrics_in_region(scene, camera, Some(viewport))
3976    }
3977
3978    /// Renders an ordinary world scene into an offscreen target.
3979    ///
3980    /// Target dimensions are physical texels. `pixel_scale` defines their
3981    /// logical viewport density independently of window DPI. Scene-local clips
3982    /// are relative to `viewport`, or to the complete logical target when no
3983    /// region is supplied. `load` explicitly controls preservation or clearing.
3984    #[allow(clippy::too_many_arguments)]
3985    pub fn render_scene_to_target(
3986        &mut self,
3987        target: &RenderTarget2d,
3988        scene: &Scene,
3989        camera: &Camera2d,
3990        pixel_scale: PhysicalPerLogical,
3991        viewport: Option<LogicalViewportRegion>,
3992        load: RenderTargetLoad,
3993    ) -> Result<RenderReport, RenderTargetError> {
3994        self.validate_render_target(target)?;
3995        if let RenderTargetLoad::Clear(color) = load
3996            && !color.is_normalized()
3997        {
3998            return Err(RenderTargetError::InvalidBackground);
3999        }
4000
4001        let frame_started_at = Instant::now();
4002        let scale = pixel_scale.get();
4003        let target_viewport = LogicalViewport::new(
4004            target.width() as f32 / scale,
4005            target.height() as f32 / scale,
4006        )
4007        .map_err(|_| RenderTargetError::Frame(RendererFrameError::InvalidViewport))?;
4008        let (local_viewport, origin) = match viewport {
4009            Some(region) => (region.viewport(), region.origin().to_vec2()),
4010            None => (target_viewport, Vec2::ZERO),
4011        };
4012        let max = origin + local_viewport.size();
4013        if !max.is_finite()
4014            || origin.x < 0.0
4015            || origin.y < 0.0
4016            || max.x > target_viewport.width()
4017            || max.y > target_viewport.height()
4018        {
4019            return Err(RenderTargetError::Frame(
4020                RendererFrameError::InvalidViewport,
4021            ));
4022        }
4023        let target_scissor = logical_viewport_scissor(
4024            origin,
4025            local_viewport,
4026            scale,
4027            target.width(),
4028            target.height(),
4029        )
4030        .ok_or(RenderTargetError::Frame(
4031            RendererFrameError::InvalidViewport,
4032        ))?;
4033        let camera_uniform =
4034            CameraUniform::new_in_region(*camera, local_viewport, origin, target_viewport).ok_or(
4035                RenderTargetError::Frame(RendererFrameError::InvalidGeometryTransform),
4036            )?;
4037
4038        let tessellation_started_at = Instant::now();
4039        if !scene_estimate_fits_streaming_device(scene, &self.device, 0, self.vertex_capacity) {
4040            return Err(RenderTargetError::Frame(
4041                RendererFrameError::GeometryCapacityTooLarge,
4042            ));
4043        }
4044        self.vertices.clear();
4045        self.draw_batches.clear();
4046        let tessellation_stats =
4047            tessellate_scene(scene, &mut self.vertices, &mut self.draw_batches)
4048                .map_err(RendererFrameError::from)
4049                .map_err(RenderTargetError::Frame)?;
4050        let tessellation = tessellation_started_at.elapsed();
4051
4052        let extents = GeometryExtents::from_vertices(&self.vertices);
4053        if !geometry_is_safe_for(
4054            extents,
4055            GeometryValidationSource::Tessellated(&self.vertices),
4056            camera_uniform,
4057        ) {
4058            return Err(RenderTargetError::Frame(
4059                RendererFrameError::InvalidGeometryTransform,
4060            ));
4061        }
4062        let upload_started_at = Instant::now();
4063        self.ensure_vertex_capacity(self.vertices.len())
4064            .map_err(RenderTargetError::Frame)?;
4065        if !self.vertices.is_empty() {
4066            self.queue
4067                .write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(&self.vertices));
4068        }
4069        let upload = upload_started_at.elapsed();
4070        let uniform_started_at = Instant::now();
4071        self.queue.write_buffer(
4072            &self.camera_uniform_buffer,
4073            0,
4074            bytemuck::bytes_of(&camera_uniform),
4075        );
4076        let camera_uniform_upload = uniform_started_at.elapsed();
4077
4078        let encode_started_at = Instant::now();
4079        let mut encoder = self
4080            .device
4081            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
4082                label: Some("sim-engine scene target encoder"),
4083            });
4084        {
4085            let load = match load {
4086                RenderTargetLoad::Load => wgpu::LoadOp::Load,
4087                RenderTargetLoad::Clear(color) => {
4088                    wgpu::LoadOp::Clear(premultiplied_wgpu_color(color))
4089                }
4090            };
4091            let color_attachment = wgpu::RenderPassColorAttachment {
4092                view: &target.view,
4093                depth_slice: None,
4094                resolve_target: None,
4095                ops: wgpu::Operations {
4096                    load,
4097                    store: wgpu::StoreOp::Store,
4098                },
4099            };
4100            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
4101                label: Some("sim-engine scene target pass"),
4102                color_attachments: &[Some(color_attachment)],
4103                depth_stencil_attachment: None,
4104                timestamp_writes: None,
4105                occlusion_query_set: None,
4106                multiview_mask: None,
4107            });
4108            if !self.vertices.is_empty() {
4109                pass.set_pipeline(&self.target_pipeline);
4110                pass.set_bind_group(0, &self.camera_bind_group, &[]);
4111                pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
4112                for batch in &self.draw_batches {
4113                    let scissor = match batch.screen_clip {
4114                        Some(clip) => {
4115                            let Some(local) = screen_clip_to_scissor(clip, local_viewport, scale)
4116                            else {
4117                                continue;
4118                            };
4119                            let Some(scissor) = offset_scissor(local, target_scissor) else {
4120                                continue;
4121                            };
4122                            scissor
4123                        }
4124                        None => target_scissor,
4125                    };
4126                    pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
4127                    pass.draw(batch.vertex_range.clone(), 0..1);
4128                }
4129            }
4130        }
4131        self.queue.submit([encoder.finish()]);
4132        let encode = encode_started_at.elapsed();
4133
4134        Ok(render_report(
4135            RenderStatus::Drawn,
4136            tessellation,
4137            upload,
4138            camera_uniform_upload,
4139            Duration::ZERO,
4140            encode,
4141            frame_started_at.elapsed(),
4142            false,
4143            true,
4144            tessellation_stats,
4145        ))
4146    }
4147
4148    fn render_with_metrics_in_region(
4149        &mut self,
4150        scene: &Scene,
4151        camera: &Camera2d,
4152        viewport: Option<LogicalViewportRegion>,
4153    ) -> Result<RenderReport, RendererFrameError> {
4154        let frame_started_at = Instant::now();
4155        let (_, _, camera_uniform) = self.surface_geometry_context(*camera, viewport)?;
4156        let tessellation_started_at = Instant::now();
4157        if !scene_estimate_fits_streaming_device(scene, &self.device, 0, self.vertex_capacity) {
4158            return Err(RendererFrameError::GeometryCapacityTooLarge);
4159        }
4160        self.vertices.clear();
4161        self.draw_batches.clear();
4162        let tessellation_stats =
4163            tessellate_scene(scene, &mut self.vertices, &mut self.draw_batches)?;
4164        let tessellation = tessellation_started_at.elapsed();
4165
4166        let geometry_extents = GeometryExtents::from_vertices(&self.vertices);
4167        if !geometry_is_safe_for(
4168            geometry_extents,
4169            GeometryValidationSource::Tessellated(&self.vertices),
4170            camera_uniform,
4171        ) {
4172            return Err(RendererFrameError::InvalidGeometryTransform);
4173        }
4174
4175        let upload_started_at = Instant::now();
4176        self.ensure_vertex_capacity(self.vertices.len())?;
4177        let upload = upload_started_at.elapsed();
4178
4179        let vertex_buffer = Arc::clone(&self.vertex_buffer);
4180        let draw_batches = std::mem::take(&mut self.draw_batches);
4181        let vertices = std::mem::take(&mut self.vertices);
4182        let result = self.draw_geometry(
4183            scene.background(),
4184            &vertex_buffer,
4185            vertices.len(),
4186            geometry_extents,
4187            GeometryValidationSource::Tessellated(&vertices),
4188            None,
4189            &draw_batches,
4190            *camera,
4191            tessellation,
4192            upload,
4193            false,
4194            true,
4195            false,
4196            Some(&vertices),
4197            tessellation_stats,
4198            frame_started_at,
4199            viewport,
4200        );
4201        self.vertices = vertices;
4202        self.draw_batches = draw_batches;
4203        result
4204    }
4205
4206    /// Tessellates a scene once and uploads immutable geometry to a dedicated GPU buffer.
4207    ///
4208    /// Preparing is appropriate for geometry that will be drawn repeatedly while
4209    /// only the camera or target dimensions change. Any shape, style, gradient,
4210    /// ordering, or clipping change requires preparing a replacement scene.
4211    pub fn prepare_scene(&self, scene: &Scene) -> Result<PreparedScene, PreparedSceneError> {
4212        prepare_scene_resources(
4213            &self.device,
4214            &self.queue,
4215            Arc::clone(&self.renderer_identity),
4216            scene,
4217        )
4218    }
4219
4220    /// Tessellates fixed logical-screen geometry once for repeated composition.
4221    pub fn prepare_screen_scene(
4222        &self,
4223        scene: &ScreenScene,
4224    ) -> Result<PreparedScreenScene, PreparedSceneError> {
4225        self.prepare_scene(scene.as_scene())
4226            .map(|scene| PreparedScreenScene { scene })
4227    }
4228
4229    /// Restores prepared logical-screen geometry on a recreated renderer.
4230    pub fn restore_prepared_screen_scene(
4231        &self,
4232        source: &PreparedScreenScene,
4233    ) -> Result<PreparedScreenScene, PreparedSceneError> {
4234        self.restore_prepared_scene(&source.scene)
4235            .map(|scene| PreparedScreenScene { scene })
4236    }
4237
4238    /// Recreates prepared GPU resources on this renderer from a retained CPU snapshot.
4239    ///
4240    /// This supports renderer recreation after device loss without requiring the
4241    /// original high-level [`Scene`]. The returned snapshot belongs to this renderer.
4242    pub fn restore_prepared_scene(
4243        &self,
4244        source: &PreparedScene,
4245    ) -> Result<PreparedScene, PreparedSceneError> {
4246        restore_prepared_scene_resources(
4247            &self.device,
4248            &self.queue,
4249            Arc::clone(&self.renderer_identity),
4250            source,
4251        )
4252    }
4253
4254    /// Recreates a dynamic mesh on this renderer from its retained CPU vertices.
4255    ///
4256    /// Use this after recreating a renderer following device loss. The returned
4257    /// mesh belongs to this renderer and preserves the source mesh's capacity so
4258    /// subsequent updates retain the same allocation behavior.
4259    pub fn restore_dynamic_mesh(
4260        &self,
4261        source: &DynamicMesh2d,
4262    ) -> Result<DynamicMesh2d, DynamicMeshError> {
4263        restore_dynamic_mesh_resources(
4264            &self.device,
4265            &self.queue,
4266            Arc::clone(&self.renderer_identity),
4267            source,
4268        )
4269    }
4270
4271    /// Creates mutable triangle-list geometry for a frequently changing visual.
4272    ///
4273    /// The vertex count must be divisible by three. The mesh is owned by this
4274    /// renderer and may only be updated or drawn through it.
4275    pub fn create_dynamic_mesh(
4276        &self,
4277        vertices: &[DynamicVertex2d],
4278    ) -> Result<DynamicMesh2d, DynamicMeshError> {
4279        self.create_dynamic_mesh_inner(vertices, None)
4280    }
4281
4282    /// Creates bounded mutable colored triangles for composition in a frame.
4283    ///
4284    /// Validation and CPU reservation complete before any GPU allocation. The
4285    /// retained budget is also enforced by every later full or partial update.
4286    pub fn create_dynamic_mesh_with_budget(
4287        &self,
4288        vertices: &[DynamicVertex2d],
4289        budget: DynamicMeshBudget,
4290    ) -> Result<DynamicMesh2d, DynamicMeshError> {
4291        self.create_dynamic_mesh_inner(vertices, Some(budget))
4292    }
4293
4294    fn create_dynamic_mesh_inner(
4295        &self,
4296        vertices: &[DynamicVertex2d],
4297        budget: Option<DynamicMeshBudget>,
4298    ) -> Result<DynamicMesh2d, DynamicMeshError> {
4299        if let Some(budget) = budget {
4300            validate_dynamic_mesh_budget(budget, vertices.len())?;
4301        }
4302        let vertex_capacity = dynamic_vertex_capacity(vertices.len())
4303            .filter(|capacity| buffer_capacity_fits::<DynamicGpu>(&self.device, *capacity))
4304            .ok_or(DynamicMeshError::CapacityTooLarge)?;
4305        let vertices = dynamic_vertices_to_gpu(vertices)?;
4306        if let Some(budget) = budget {
4307            validate_dynamic_retained_capacity(budget, &vertices)?;
4308        }
4309        let vertex_buffer = Arc::new(create_dynamic_vertex_buffer(&self.device, vertex_capacity));
4310        if !vertices.is_empty() {
4311            self.queue
4312                .write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(&vertices));
4313            submit_pending_uploads(&self.queue);
4314        }
4315        Ok(DynamicMesh2d {
4316            renderer_identity: Arc::clone(&self.renderer_identity),
4317            geometry_extents: GeometryExtents::from_dynamic_vertices(&vertices),
4318            geometry_validation_cache: GeometryValidationCache::default(),
4319            vertex_buffer,
4320            vertices,
4321            vertex_capacity,
4322            budget,
4323        })
4324    }
4325
4326    /// Replaces all dynamic mesh vertices, growing GPU capacity only when needed.
4327    pub fn update_dynamic_mesh(
4328        &self,
4329        mesh: &mut DynamicMesh2d,
4330        vertices: &[DynamicVertex2d],
4331    ) -> Result<(), DynamicMeshError> {
4332        self.update_dynamic_mesh_with_metrics(mesh, vertices)
4333            .map(|_| ())
4334    }
4335
4336    /// Replaces all dynamic mesh vertices and returns CPU-side update metrics.
4337    pub fn update_dynamic_mesh_with_metrics(
4338        &self,
4339        mesh: &mut DynamicMesh2d,
4340        vertices: &[DynamicVertex2d],
4341    ) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
4342        self.validate_dynamic_mesh(mesh)?;
4343        replace_dynamic_mesh_resources(&self.device, &self.queue, mesh, vertices)
4344    }
4345
4346    /// Replaces a contiguous vertex range without reallocating the mesh buffer.
4347    ///
4348    /// The range must stay inside the current triangle list and its length must
4349    /// preserve triangle alignment, so callers cannot create partial triangles.
4350    pub fn update_dynamic_mesh_range(
4351        &self,
4352        mesh: &mut DynamicMesh2d,
4353        first_vertex: usize,
4354        vertices: &[DynamicVertex2d],
4355    ) -> Result<(), DynamicMeshError> {
4356        self.update_dynamic_mesh_range_with_metrics(mesh, first_vertex, vertices)
4357            .map(|_| ())
4358    }
4359
4360    /// Replaces a triangle-aligned range and returns CPU-side update metrics.
4361    pub fn update_dynamic_mesh_range_with_metrics(
4362        &self,
4363        mesh: &mut DynamicMesh2d,
4364        first_vertex: usize,
4365        vertices: &[DynamicVertex2d],
4366    ) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
4367        let update_started_at = Instant::now();
4368        self.validate_dynamic_mesh(mesh)?;
4369        let end = first_vertex
4370            .checked_add(vertices.len())
4371            .ok_or(DynamicMeshError::UpdateRangeOutOfBounds)?;
4372        if !first_vertex.is_multiple_of(3)
4373            || !vertices.len().is_multiple_of(3)
4374            || end > mesh.vertices.len()
4375        {
4376            return Err(DynamicMeshError::UpdateRangeOutOfBounds);
4377        }
4378        if let Some(budget) = mesh.budget {
4379            validate_dynamic_mesh_budget(budget, mesh.vertices.len())?;
4380            let upload_bytes = dynamic_mesh_bytes(vertices.len())?;
4381            if upload_bytes > budget.max_upload_bytes {
4382                return Err(DynamicMeshError::BudgetExceeded {
4383                    resource: DynamicMeshBudgetResource::UploadBytes,
4384                    limit: budget.max_upload_bytes,
4385                    actual: upload_bytes,
4386                });
4387            }
4388        }
4389        let vertices = dynamic_vertices_to_gpu(vertices)?;
4390        if !vertices.is_empty() {
4391            let offset = (first_vertex * std::mem::size_of::<DynamicGpu>()) as wgpu::BufferAddress;
4392            self.queue
4393                .write_buffer(&mesh.vertex_buffer, offset, bytemuck::cast_slice(&vertices));
4394            submit_pending_uploads(&self.queue);
4395            mesh.vertices[first_vertex..end].copy_from_slice(&vertices);
4396            mesh.geometry_extents = GeometryExtents::from_dynamic_vertices(&mesh.vertices);
4397            mesh.geometry_validation_cache.clear();
4398        }
4399        Ok(DynamicMeshUpdateReport {
4400            vertex_count: mesh.vertices.len(),
4401            upload: update_started_at.elapsed(),
4402            reallocated: false,
4403        })
4404    }
4405
4406    /// Draws dynamic triangle-list geometry with a normalized clear color.
4407    ///
4408    /// Every potentially visible triangle must remain fully inside the full
4409    /// surface clip volume and have a portable projected orientation. A
4410    /// hardware-clipped or ambiguous triangle returns
4411    /// `DynamicMeshRenderError::Frame(RendererFrameError::InvalidGeometryTransform)`.
4412    pub fn render_dynamic_mesh(
4413        &mut self,
4414        mesh: &DynamicMesh2d,
4415        background: Color,
4416        camera: &Camera2d,
4417    ) -> Result<RenderStatus, DynamicMeshRenderError> {
4418        self.render_dynamic_mesh_with_metrics(mesh, background, camera)
4419            .map(RenderReport::status)
4420    }
4421
4422    /// Draws dynamic triangle-list geometry and returns per-frame CPU metrics.
4423    ///
4424    /// Full-surface clip-volume crossing and association-dependent projected
4425    /// topology are rejected as
4426    /// `DynamicMeshRenderError::Frame(RendererFrameError::InvalidGeometryTransform)`.
4427    pub fn render_dynamic_mesh_with_metrics(
4428        &mut self,
4429        mesh: &DynamicMesh2d,
4430        background: Color,
4431        camera: &Camera2d,
4432    ) -> Result<RenderReport, DynamicMeshRenderError> {
4433        self.validate_dynamic_mesh(mesh)
4434            .map_err(|_| DynamicMeshRenderError::RendererMismatch)?;
4435        if !background.is_normalized() {
4436            return Err(DynamicMeshRenderError::InvalidBackground);
4437        }
4438        let draw_batches = (!mesh.vertices.is_empty()).then_some(PreparedDrawBatch {
4439            vertex_range: 0..mesh.vertices.len() as u32,
4440            screen_clip: None,
4441        });
4442        self.draw_geometry(
4443            background,
4444            &mesh.vertex_buffer,
4445            mesh.vertices.len(),
4446            mesh.geometry_extents,
4447            GeometryValidationSource::Dynamic(&mesh.vertices),
4448            Some(&mesh.geometry_validation_cache),
4449            draw_batches.as_slice(),
4450            *camera,
4451            Duration::ZERO,
4452            Duration::ZERO,
4453            false,
4454            true,
4455            true,
4456            None,
4457            TessellationStats::default(),
4458            Instant::now(),
4459            None,
4460        )
4461        .map_err(DynamicMeshRenderError::Frame)
4462    }
4463
4464    /// Creates an instanced particle field owned by this renderer.
4465    ///
4466    /// Each instance draws as one screen-space circle quad through a single GPU
4467    /// draw call. The retained CPU snapshot enables later restoration on a
4468    /// recreated renderer.
4469    pub fn create_particle_field(
4470        &self,
4471        instances: &[ParticleInstance2d],
4472    ) -> Result<ParticleField2d, ParticleFieldError> {
4473        self.create_particle_field_with_budget(instances, ParticleRenderBudget::UNBOUNDED)
4474    }
4475
4476    /// Creates an instanced particle field with hard retained-CPU, GPU-memory,
4477    /// upload, visible-instance, and visibility-work limits.
4478    pub fn create_particle_field_with_budget(
4479        &self,
4480        instances: &[ParticleInstance2d],
4481        budget: ParticleRenderBudget,
4482    ) -> Result<ParticleField2d, ParticleFieldError> {
4483        validate_particle_retained_count(instances.len(), budget)?;
4484        let instance_capacity = particle_budgeted_capacity(instances.len(), budget)
4485            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
4486            .ok_or(ParticleFieldError::CapacityTooLarge)?;
4487        let instances = particle_instances_to_gpu(instances)?;
4488        let visible_instances = allocate_particle_staging(instances.len(), budget)?;
4489        validate_particle_retained_capacities(
4490            instances.capacity(),
4491            visible_instances.capacity(),
4492            budget,
4493        )?;
4494        let instance_buffer = Arc::new(create_particle_instance_buffer(
4495            &self.device,
4496            instance_capacity,
4497        ));
4498        Ok(ParticleField2d {
4499            renderer_identity: Arc::clone(&self.renderer_identity),
4500            instance_buffer,
4501            statistics: particle_idle_statistics(instances.len()),
4502            instances,
4503            visible_instances,
4504            instance_capacity,
4505            budget,
4506        })
4507    }
4508
4509    /// Replaces a particle field's hard resource budget, shrinking memory when required.
4510    pub fn set_particle_field_budget(
4511        &self,
4512        field: &mut ParticleField2d,
4513        budget: ParticleRenderBudget,
4514    ) -> Result<(), ParticleFieldError> {
4515        self.validate_particle_field(field)?;
4516        validate_particle_retained_count(field.instances.len(), budget)?;
4517        let desired_capacity = particle_budgeted_capacity(field.instances.len(), budget)
4518            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
4519            .ok_or(ParticleFieldError::CapacityTooLarge)?;
4520        let visible_instances = allocate_particle_staging(field.instances.len(), budget)?;
4521        let replacement_instances = compact_particle_instances(
4522            &field.instances,
4523            field.instances.capacity(),
4524            visible_instances.capacity(),
4525            budget,
4526        )?;
4527        let replacement_buffer = (desired_capacity != field.instance_capacity).then(|| {
4528            Arc::new(create_particle_instance_buffer(
4529                &self.device,
4530                desired_capacity,
4531            ))
4532        });
4533        if let Some(instance_buffer) = replacement_buffer {
4534            field.instance_buffer = instance_buffer;
4535            field.instance_capacity = desired_capacity;
4536        }
4537        if let Some(instances) = replacement_instances {
4538            field.instances = instances;
4539        }
4540        field.budget = budget;
4541        field.visible_instances = visible_instances;
4542        field.statistics = particle_idle_statistics(field.instances.len());
4543        Ok(())
4544    }
4545
4546    /// Replaces all particle instances, reusing GPU capacity whenever possible.
4547    pub fn update_particle_field(
4548        &self,
4549        field: &mut ParticleField2d,
4550        instances: &[ParticleInstance2d],
4551    ) -> Result<ParticleStatistics, ParticleFieldError> {
4552        self.update_particle_field_with_metrics(field, instances)
4553            .map(|report| report.statistics())
4554    }
4555
4556    /// Replaces all particle instances and returns CPU-side preparation metrics.
4557    pub fn update_particle_field_with_metrics(
4558        &self,
4559        field: &mut ParticleField2d,
4560        instances: &[ParticleInstance2d],
4561    ) -> Result<ParticleFieldUpdateReport, ParticleFieldError> {
4562        let update_started_at = Instant::now();
4563        self.validate_particle_field(field)?;
4564        validate_particle_retained_count(instances.len(), field.budget)?;
4565        let desired_capacity = particle_budgeted_capacity(instances.len(), field.budget)
4566            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
4567            .ok_or(ParticleFieldError::CapacityTooLarge)?;
4568        let instances = particle_instances_to_gpu(instances)?;
4569        let visible_instances = allocate_particle_staging(instances.len(), field.budget)?;
4570        validate_particle_retained_capacities(
4571            instances.capacity(),
4572            visible_instances.capacity(),
4573            field.budget,
4574        )?;
4575        let reallocated = desired_capacity > field.instance_capacity;
4576        let replacement_buffer = reallocated.then(|| {
4577            Arc::new(create_particle_instance_buffer(
4578                &self.device,
4579                desired_capacity,
4580            ))
4581        });
4582        if let Some(instance_buffer) = replacement_buffer {
4583            field.instance_buffer = instance_buffer;
4584            field.instance_capacity = desired_capacity;
4585        }
4586        field.statistics = particle_idle_statistics(instances.len());
4587        field.instances = instances;
4588        field.visible_instances = visible_instances;
4589        Ok(ParticleFieldUpdateReport {
4590            statistics: field.statistics,
4591            preparation: update_started_at.elapsed(),
4592            reallocated,
4593        })
4594    }
4595
4596    /// Replaces a contiguous particle range without reallocating its GPU buffer.
4597    pub fn update_particle_field_range(
4598        &self,
4599        field: &mut ParticleField2d,
4600        first_instance: usize,
4601        instances: &[ParticleInstance2d],
4602    ) -> Result<ParticleStatistics, ParticleFieldError> {
4603        self.update_particle_field_range_with_metrics(field, first_instance, instances)
4604            .map(|report| report.statistics())
4605    }
4606
4607    /// Replaces a particle range and returns CPU-side preparation metrics.
4608    pub fn update_particle_field_range_with_metrics(
4609        &self,
4610        field: &mut ParticleField2d,
4611        first_instance: usize,
4612        instances: &[ParticleInstance2d],
4613    ) -> Result<ParticleFieldUpdateReport, ParticleFieldError> {
4614        let update_started_at = Instant::now();
4615        self.validate_particle_field(field)?;
4616        let range = particle_update_range(first_instance, instances.len(), field.instances.len())?;
4617        let instances = particle_instances_to_gpu(instances)?;
4618        if !instances.is_empty() {
4619            field.instances[range].copy_from_slice(&instances);
4620        }
4621        field.statistics = particle_idle_statistics(field.instances.len());
4622        Ok(ParticleFieldUpdateReport {
4623            statistics: field.statistics,
4624            preparation: update_started_at.elapsed(),
4625            reallocated: false,
4626        })
4627    }
4628
4629    /// Recreates a particle field on this renderer from retained CPU instances.
4630    pub fn restore_particle_field(
4631        &self,
4632        source: &ParticleField2d,
4633    ) -> Result<ParticleField2d, ParticleFieldError> {
4634        restore_particle_field_resources(
4635            &self.device,
4636            &self.queue,
4637            Arc::clone(&self.renderer_identity),
4638            source,
4639        )
4640    }
4641
4642    /// Creates a single-channel floating-point texture from a validated scalar grid.
4643    pub fn create_scalar_field_texture(
4644        &self,
4645        field: ScalarField,
4646    ) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
4647        create_scalar_field_texture_resources(
4648            &self.device,
4649            &self.queue,
4650            Arc::clone(&self.renderer_identity),
4651            field,
4652        )
4653    }
4654
4655    /// Creates an offscreen target with physical texture dimensions.
4656    pub fn create_render_target(
4657        &self,
4658        width: u32,
4659        height: u32,
4660    ) -> Result<RenderTarget2d, RenderTargetError> {
4661        if width == 0 || height == 0 {
4662            return Err(RenderTargetError::ZeroDimension);
4663        }
4664        if width > self.device.limits().max_texture_dimension_2d
4665            || height > self.device.limits().max_texture_dimension_2d
4666        {
4667            return Err(RenderTargetError::DimensionsTooLarge);
4668        }
4669        let allocation_bytes = render_target_allocation_bytes(self.config.format, width, height)
4670            .ok_or(RenderTargetError::DimensionsTooLarge)?;
4671        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
4672            label: Some("sim-engine render target"),
4673            size: wgpu::Extent3d {
4674                width,
4675                height,
4676                depth_or_array_layers: 1,
4677            },
4678            mip_level_count: 1,
4679            sample_count: 1,
4680            dimension: wgpu::TextureDimension::D2,
4681            format: self.config.format,
4682            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
4683                | wgpu::TextureUsages::TEXTURE_BINDING
4684                | wgpu::TextureUsages::COPY_SRC,
4685            view_formats: &[],
4686        });
4687        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4688        Ok(RenderTarget2d {
4689            renderer_identity: Arc::clone(&self.renderer_identity),
4690            resource_identity: Arc::new(()),
4691            _texture: texture,
4692            view,
4693            width,
4694            height,
4695            allocation_bytes,
4696        })
4697    }
4698
4699    /// Creates an empty ping-pong target pair for temporal accumulation.
4700    pub fn create_trail_buffer(
4701        &mut self,
4702        width: u32,
4703        height: u32,
4704    ) -> Result<TrailBuffer2d, RenderTargetError> {
4705        let front = self.create_render_target(width, height)?;
4706        let back = self.create_render_target(width, height)?;
4707        let trails = TrailBuffer2d {
4708            renderer_identity: Arc::clone(&self.renderer_identity),
4709            front,
4710            back,
4711        };
4712        self.draw_clear_trail_buffer(&trails, Color::rgba(0.0, 0.0, 0.0, 0.0), Instant::now());
4713        Ok(trails)
4714    }
4715
4716    /// Recreates an empty target with the source dimensions after device recovery.
4717    ///
4718    /// GPU pixels are deliberately not retained; callers redraw their source
4719    /// state into the restored target.
4720    pub fn restore_render_target(
4721        &self,
4722        source: &RenderTarget2d,
4723    ) -> Result<RenderTarget2d, RenderTargetError> {
4724        self.create_render_target(source.width(), source.height())
4725    }
4726
4727    /// Recreates an empty, deterministically cleared trail buffer after recovery.
4728    pub fn restore_trail_buffer(
4729        &mut self,
4730        source: &TrailBuffer2d,
4731    ) -> Result<TrailBuffer2d, RenderTargetError> {
4732        self.create_trail_buffer(source.width(), source.height())
4733    }
4734
4735    /// Retains one bounded frame of history and composites a fresh source target.
4736    ///
4737    /// `retention` and `source_opacity` must be finite values in `0.0..=1.0`.
4738    /// The source must be a distinct target; use [`WgpuRenderer::clear_trail_buffer`]
4739    /// to discard accumulated history deterministically.
4740    pub fn accumulate_trail_buffer(
4741        &mut self,
4742        trails: &mut TrailBuffer2d,
4743        source: &RenderTarget2d,
4744        retention: f32,
4745        source_opacity: f32,
4746        source_blend: BlendMode,
4747    ) -> Result<RenderReport, RenderTargetError> {
4748        self.validate_trail_buffer(trails)?;
4749        self.validate_render_target(source)?;
4750        if Arc::ptr_eq(&source.resource_identity, &trails.front.resource_identity)
4751            || Arc::ptr_eq(&source.resource_identity, &trails.back.resource_identity)
4752        {
4753            return Err(RenderTargetError::SourceAliasesDestination);
4754        }
4755        if !retention.is_finite()
4756            || !(0.0..=1.0).contains(&retention)
4757            || !source_opacity.is_finite()
4758            || !(0.0..=1.0).contains(&source_opacity)
4759        {
4760            return Err(RenderTargetError::InvalidOpacity);
4761        }
4762        Ok(self.draw_trail_accumulation(
4763            trails,
4764            source,
4765            retention,
4766            source_opacity,
4767            source_blend,
4768            Instant::now(),
4769        ))
4770    }
4771
4772    /// Clears both ping-pong targets, resetting all retained temporal history.
4773    pub fn clear_trail_buffer(
4774        &mut self,
4775        trails: &mut TrailBuffer2d,
4776        color: Color,
4777    ) -> Result<RenderReport, RenderTargetError> {
4778        self.validate_trail_buffer(trails)?;
4779        if !color.is_normalized() {
4780            return Err(RenderTargetError::InvalidBackground);
4781        }
4782        Ok(self.draw_clear_trail_buffer(trails, color, Instant::now()))
4783    }
4784
4785    /// Presents the most recently accumulated temporal target.
4786    pub fn compose_trail_buffer(
4787        &mut self,
4788        trails: &TrailBuffer2d,
4789        blend_mode: BlendMode,
4790        opacity: f32,
4791        background: Color,
4792    ) -> Result<RenderReport, RenderTargetError> {
4793        self.validate_trail_buffer(trails)?;
4794        self.compose_render_target(&trails.front, blend_mode, opacity, background)
4795    }
4796
4797    /// Replaces scalar data, recreating the texture only when dimensions change.
4798    pub fn update_scalar_field_texture(
4799        &self,
4800        texture: &mut ScalarFieldTexture,
4801        field: ScalarField,
4802    ) -> Result<ScalarFieldUploadReport, ScalarFieldTextureError> {
4803        let upload_started_at = Instant::now();
4804        self.validate_scalar_field_texture(texture)?;
4805        validate_scalar_field_device_extent(&self.device, &field)?;
4806        if !scalar_field_sources_are_portable(&field) {
4807            return Err(ScalarFieldTextureError::NonPortableValue);
4808        }
4809        let field = compact_scalar_field_for_retention(field)?;
4810        let (source_minimum, source_maximum) = field.value_range();
4811        let reallocated = texture.width() != field.width() || texture.height() != field.height();
4812        if reallocated {
4813            texture.texture = create_scalar_field_texture(&self.device, &field)?;
4814        }
4815        upload_scalar_field_texture(&self.queue, &texture.texture, &field)?;
4816        texture.field = field;
4817        texture.source_minimum = source_minimum;
4818        texture.source_maximum = source_maximum;
4819        Ok(ScalarFieldUploadReport {
4820            upload: upload_started_at.elapsed(),
4821            reallocated,
4822        })
4823    }
4824
4825    /// Updates a rectangular scalar texture region without recreating it.
4826    pub fn update_scalar_field_texture_region(
4827        &self,
4828        texture: &mut ScalarFieldTexture,
4829        x: usize,
4830        y: usize,
4831        width: usize,
4832        height: usize,
4833        values: &[f32],
4834    ) -> Result<ScalarFieldUploadReport, ScalarFieldTextureError> {
4835        let upload_started_at = Instant::now();
4836        self.validate_scalar_field_texture(texture)?;
4837        if values.iter().any(|value| !value.is_finite()) {
4838            return Err(ScalarFieldTextureError::NonFiniteUpdateValue);
4839        }
4840        if values
4841            .iter()
4842            .copied()
4843            .any(|value| !is_portable_shader_source(value))
4844        {
4845            return Err(ScalarFieldTextureError::NonPortableValue);
4846        }
4847        validate_scalar_field_texture_region(
4848            texture.width(),
4849            texture.height(),
4850            x,
4851            y,
4852            width,
4853            height,
4854            values.len(),
4855        )?;
4856        let update_minimum = values.iter().copied().fold(f32::INFINITY, f32::min);
4857        let update_maximum = values.iter().copied().fold(f32::NEG_INFINITY, f32::max);
4858        let overwrites_extremum = (y..y + height).any(|row| {
4859            let start = row * texture.width() + x;
4860            texture.field.values()[start..start + width]
4861                .iter()
4862                .any(|value| *value == texture.source_minimum || *value == texture.source_maximum)
4863        });
4864        let (source_minimum, source_maximum) = if overwrites_extremum {
4865            scalar_region_result_range(&texture.field, x, y, width, height, values)
4866        } else {
4867            (
4868                texture.source_minimum.min(update_minimum),
4869                texture.source_maximum.max(update_maximum),
4870            )
4871        };
4872        let source_extent = f64::from(source_maximum) - f64::from(source_minimum);
4873        if !source_extent.is_finite() || source_extent > f64::from(MAX_PORTABLE_SHADER_VALUE) {
4874            return Err(ScalarFieldTextureError::NonPortableValue);
4875        }
4876        texture
4877            .field
4878            .replace_region(x, y, width, height, values)
4879            .map_err(|error| match error {
4880                crate::ScalarFieldError::InvalidValueCount { .. } => {
4881                    ScalarFieldTextureError::InvalidUpdateValueCount
4882                }
4883                crate::ScalarFieldError::NonFiniteValue => {
4884                    ScalarFieldTextureError::NonFiniteUpdateValue
4885                }
4886                _ => ScalarFieldTextureError::UpdateRegionOutOfBounds,
4887            })?;
4888        upload_scalar_field_texture_region(
4889            &self.queue,
4890            &texture.texture,
4891            x,
4892            y,
4893            width,
4894            height,
4895            values,
4896        )?;
4897        texture.source_minimum = source_minimum;
4898        texture.source_maximum = source_maximum;
4899        Ok(ScalarFieldUploadReport {
4900            upload: upload_started_at.elapsed(),
4901            reallocated: false,
4902        })
4903    }
4904
4905    /// Recreates a scalar texture on this renderer from its retained CPU grid.
4906    pub fn restore_scalar_field_texture(
4907        &self,
4908        source: &ScalarFieldTexture,
4909    ) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
4910        validate_scalar_field_device_extent(&self.device, &source.field)?;
4911        let field = clone_scalar_field_for_restore(&source.field)?;
4912        self.create_scalar_field_texture(field)
4913    }
4914
4915    /// Draws a scalar texture across the logical viewport through a color map.
4916    ///
4917    /// `value_range` maps `minimum` to the first color-map entry and `maximum`
4918    /// to the last. Values outside the range clamp to those endpoints.
4919    pub fn render_scalar_field_texture(
4920        &mut self,
4921        texture: &ScalarFieldTexture,
4922        color_map: &ColorMap,
4923        value_range: (f32, f32),
4924        background: Color,
4925    ) -> Result<RenderStatus, ScalarFieldRenderError> {
4926        self.render_scalar_field_texture_with_metrics(texture, color_map, value_range, background)
4927            .map(RenderReport::status)
4928    }
4929
4930    /// Draws a scalar texture and returns normal CPU-side renderer metrics.
4931    pub fn render_scalar_field_texture_with_metrics(
4932        &mut self,
4933        texture: &ScalarFieldTexture,
4934        color_map: &ColorMap,
4935        (minimum, maximum): (f32, f32),
4936        background: Color,
4937    ) -> Result<RenderReport, ScalarFieldRenderError> {
4938        self.validate_scalar_field_texture(texture)
4939            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
4940        let value_extent = scalar_value_range_extent(minimum, maximum)
4941            .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
4942        if !scalar_normalization_is_portable(texture, minimum, value_extent) {
4943            return Err(ScalarFieldRenderError::InvalidValueRange { minimum, maximum });
4944        }
4945        if !background.is_normalized() {
4946            return Err(ScalarFieldRenderError::InvalidBackground);
4947        }
4948        self.draw_scalar_field_texture(
4949            texture,
4950            color_map,
4951            minimum,
4952            value_extent,
4953            ScalarFieldSampling::Nearest,
4954            background,
4955            Instant::now(),
4956        )
4957        .map_err(ScalarFieldRenderError::Frame)
4958    }
4959
4960    /// Draws a scalar texture with an explicit texel sampling mode.
4961    pub fn render_scalar_field_texture_with_sampling(
4962        &mut self,
4963        texture: &ScalarFieldTexture,
4964        color_map: &ColorMap,
4965        (minimum, maximum): (f32, f32),
4966        sampling: ScalarFieldSampling,
4967        background: Color,
4968    ) -> Result<RenderStatus, ScalarFieldRenderError> {
4969        self.validate_scalar_field_texture(texture)
4970            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
4971        let value_extent = scalar_value_range_extent(minimum, maximum)
4972            .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
4973        if !scalar_normalization_is_portable(texture, minimum, value_extent) {
4974            return Err(ScalarFieldRenderError::InvalidValueRange { minimum, maximum });
4975        }
4976        if !background.is_normalized() {
4977            return Err(ScalarFieldRenderError::InvalidBackground);
4978        }
4979        self.draw_scalar_field_texture(
4980            texture,
4981            color_map,
4982            minimum,
4983            value_extent,
4984            sampling,
4985            background,
4986            Instant::now(),
4987        )
4988        .map(RenderReport::status)
4989        .map_err(ScalarFieldRenderError::Frame)
4990    }
4991
4992    /// Renders a scalar heatmap into an offscreen target instead of presenting it.
4993    pub fn render_scalar_field_texture_to_target(
4994        &mut self,
4995        target: &RenderTarget2d,
4996        texture: &ScalarFieldTexture,
4997        color_map: &ColorMap,
4998        value_range: (f32, f32),
4999        background: Color,
5000    ) -> Result<RenderReport, ScalarFieldRenderError> {
5001        self.render_scalar_field_texture_to_target_with_sampling(
5002            target,
5003            texture,
5004            color_map,
5005            value_range,
5006            ScalarFieldSampling::Nearest,
5007            background,
5008        )
5009    }
5010
5011    /// Renders a scalar heatmap into a target with explicit source sampling.
5012    pub fn render_scalar_field_texture_to_target_with_sampling(
5013        &mut self,
5014        target: &RenderTarget2d,
5015        texture: &ScalarFieldTexture,
5016        color_map: &ColorMap,
5017        (minimum, maximum): (f32, f32),
5018        sampling: ScalarFieldSampling,
5019        background: Color,
5020    ) -> Result<RenderReport, ScalarFieldRenderError> {
5021        self.validate_render_target(target)
5022            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
5023        self.validate_scalar_field_texture(texture)
5024            .map_err(|_| ScalarFieldRenderError::RendererMismatch)?;
5025        let value_extent = scalar_value_range_extent(minimum, maximum)
5026            .ok_or(ScalarFieldRenderError::InvalidValueRange { minimum, maximum })?;
5027        if !scalar_normalization_is_portable(texture, minimum, value_extent) {
5028            return Err(ScalarFieldRenderError::InvalidValueRange { minimum, maximum });
5029        }
5030        if !background.is_normalized() {
5031            return Err(ScalarFieldRenderError::InvalidBackground);
5032        }
5033        Ok(self.draw_scalar_field_texture_to_target(
5034            target,
5035            texture,
5036            color_map,
5037            minimum,
5038            value_extent,
5039            sampling,
5040            background,
5041            Instant::now(),
5042        ))
5043    }
5044
5045    /// Composes a previously rendered target over the presentation surface.
5046    pub fn compose_render_target(
5047        &mut self,
5048        target: &RenderTarget2d,
5049        blend_mode: BlendMode,
5050        opacity: f32,
5051        background: Color,
5052    ) -> Result<RenderReport, RenderTargetError> {
5053        self.validate_render_target(target)?;
5054        if !opacity.is_finite() || !(0.0..=1.0).contains(&opacity) {
5055            return Err(RenderTargetError::InvalidOpacity);
5056        }
5057        if !background.is_normalized() {
5058            return Err(RenderTargetError::InvalidBackground);
5059        }
5060        self.draw_composed_render_target(target, blend_mode, opacity, background, Instant::now())
5061            .map_err(RenderTargetError::Frame)
5062    }
5063
5064    /// Draws a particle field with a normalized clear color.
5065    pub fn render_particle_field(
5066        &mut self,
5067        field: &mut ParticleField2d,
5068        background: Color,
5069        camera: &Camera2d,
5070    ) -> Result<RenderStatus, ParticleFieldRenderError> {
5071        self.render_particle_field_with_metrics(field, background, camera)
5072            .map(RenderReport::status)
5073    }
5074
5075    /// Draws a particle field and returns regular per-frame renderer metrics.
5076    pub fn render_particle_field_with_metrics(
5077        &mut self,
5078        field: &mut ParticleField2d,
5079        background: Color,
5080        camera: &Camera2d,
5081    ) -> Result<RenderReport, ParticleFieldRenderError> {
5082        self.validate_particle_field(field)
5083            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
5084        if !background.is_normalized() {
5085            return Err(ParticleFieldRenderError::InvalidBackground);
5086        }
5087        self.draw_particle_field(background, field, *camera, Instant::now())
5088            .map_err(|error| match error {
5089                RendererFrameError::InvalidGeometryTransform => {
5090                    ParticleFieldRenderError::InvalidGeometryTransform
5091                }
5092                other => ParticleFieldRenderError::Frame(other),
5093            })
5094    }
5095
5096    /// Draws a particle field into an offscreen target.
5097    ///
5098    /// Target dimensions may be lower than the presentation surface to bound
5099    /// raster cost. Camera coordinates and particle radii remain expressed in
5100    /// logical presentation pixels, so composing the target back to the surface
5101    /// preserves layout while trading only raster resolution.
5102    pub fn render_particle_field_to_target(
5103        &mut self,
5104        target: &RenderTarget2d,
5105        field: &mut ParticleField2d,
5106        camera: &Camera2d,
5107        load: RenderTargetLoad,
5108    ) -> Result<RenderReport, ParticleFieldRenderError> {
5109        self.validate_render_target(target)
5110            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
5111        self.validate_particle_field(field)
5112            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
5113        if matches!(load, RenderTargetLoad::Clear(color) if !color.is_normalized()) {
5114            return Err(ParticleFieldRenderError::InvalidBackground);
5115        }
5116        self.draw_particle_field_to_target(target, field, *camera, load, Instant::now())
5117            .map_err(|error| match error {
5118                RendererFrameError::InvalidGeometryTransform => {
5119                    ParticleFieldRenderError::InvalidGeometryTransform
5120                }
5121                other => ParticleFieldRenderError::Frame(other),
5122            })
5123    }
5124
5125    /// Draws geometry previously uploaded by [`WgpuRenderer::prepare_scene`].
5126    ///
5127    /// Camera and viewport changes are applied by the vertex shader and do not
5128    /// rebuild or re-upload the prepared geometry.
5129    pub fn render_prepared(
5130        &mut self,
5131        scene: &PreparedScene,
5132        camera: &Camera2d,
5133    ) -> Result<RenderStatus, PreparedSceneRenderError> {
5134        self.render_prepared_with_metrics(scene, camera)
5135            .map(RenderReport::status)
5136    }
5137
5138    /// Draws prepared logical-screen geometry independently of a world camera.
5139    ///
5140    /// The prepared resource must have been built from a [`ScreenScene`]. The
5141    /// renderer cannot infer the original coordinate space from raw prepared
5142    /// vertices, so passing world-space geometry is a caller contract error.
5143    pub fn render_prepared_screen_scene(
5144        &mut self,
5145        scene: &PreparedScreenScene,
5146    ) -> Result<RenderStatus, PreparedSceneRenderError> {
5147        let (width, height) = self.logical_size();
5148        let viewport = LogicalViewport::new(width, height).map_err(|_| {
5149            PreparedSceneRenderError::Frame(RendererFrameError::InvalidGeometryTransform)
5150        })?;
5151        let camera = screen_camera(viewport).map_err(|_| {
5152            PreparedSceneRenderError::Frame(RendererFrameError::InvalidGeometryTransform)
5153        })?;
5154        self.render_prepared(&scene.scene, &camera)
5155    }
5156
5157    /// Draws prepared geometry and reports per-frame CPU timing.
5158    ///
5159    /// Tessellation and geometry upload durations are zero because both happened
5160    /// in [`WgpuRenderer::prepare_scene`]. The camera uniform is still updated
5161    /// once per frame.
5162    pub fn render_prepared_with_metrics(
5163        &mut self,
5164        scene: &PreparedScene,
5165        camera: &Camera2d,
5166    ) -> Result<RenderReport, PreparedSceneRenderError> {
5167        if !prepared_scene_belongs_to(&self.renderer_identity, &scene.renderer_identity) {
5168            return Err(PreparedSceneRenderError::RendererMismatch);
5169        }
5170
5171        self.draw_geometry(
5172            scene.background,
5173            &scene.vertex_buffer,
5174            scene.vertex_count,
5175            scene.geometry_extents,
5176            GeometryValidationSource::Tessellated(&scene.vertices),
5177            Some(&scene.geometry_validation_cache),
5178            &scene.draw_batches,
5179            *camera,
5180            Duration::ZERO,
5181            Duration::ZERO,
5182            true,
5183            false,
5184            false,
5185            None,
5186            scene.tessellation,
5187            Instant::now(),
5188            None,
5189        )
5190        .map_err(PreparedSceneRenderError::Frame)
5191    }
5192
5193    fn surface_geometry_context(
5194        &self,
5195        camera: Camera2d,
5196        viewport_region: Option<LogicalViewportRegion>,
5197    ) -> Result<(LogicalViewport, ScissorRect, CameraUniform), RendererFrameError> {
5198        let (logical_width, logical_height) = self.logical_size();
5199        let target_viewport = LogicalViewport::new(logical_width, logical_height)
5200            .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
5201        let (viewport, viewport_origin) = match viewport_region {
5202            Some(region) => (region.viewport(), region.origin().to_vec2()),
5203            None => (target_viewport, Vec2::ZERO),
5204        };
5205        let viewport_max = viewport_origin + viewport.size();
5206        if !viewport_origin.is_finite()
5207            || !viewport_max.is_finite()
5208            || viewport_origin.x < 0.0
5209            || viewport_origin.y < 0.0
5210            || viewport_max.x > target_viewport.width()
5211            || viewport_max.y > target_viewport.height()
5212        {
5213            return Err(RendererFrameError::InvalidViewport);
5214        }
5215        let viewport_scissor = logical_viewport_scissor(
5216            viewport_origin,
5217            viewport,
5218            self.scale_factor as f32,
5219            self.config.width,
5220            self.config.height,
5221        )
5222        .ok_or(RendererFrameError::InvalidViewport)?;
5223        let camera_uniform =
5224            CameraUniform::new_in_region(camera, viewport, viewport_origin, target_viewport)
5225                .ok_or(RendererFrameError::InvalidGeometryTransform)?;
5226        Ok((viewport, viewport_scissor, camera_uniform))
5227    }
5228
5229    #[allow(clippy::too_many_arguments)]
5230    fn draw_geometry(
5231        &mut self,
5232        background: Color,
5233        vertex_buffer: &wgpu::Buffer,
5234        vertex_count: usize,
5235        geometry_extents: GeometryExtents,
5236        geometry_validation: GeometryValidationSource<'_>,
5237        geometry_validation_cache: Option<&GeometryValidationCache>,
5238        draw_batches: &[PreparedDrawBatch],
5239        camera: Camera2d,
5240        tessellation: Duration,
5241        mut upload: Duration,
5242        geometry_reused: bool,
5243        geometry_streamed: bool,
5244        uses_dynamic_pipeline: bool,
5245        pending_vertex_upload: Option<&[Vertex]>,
5246        tessellation_stats: TessellationStats,
5247        frame_started_at: Instant,
5248        viewport_region: Option<LogicalViewportRegion>,
5249    ) -> Result<RenderReport, RendererFrameError> {
5250        let (viewport, viewport_scissor, camera_uniform) =
5251            self.surface_geometry_context(camera, viewport_region)?;
5252        if !geometry_is_safe_for_cached(
5253            geometry_validation_cache,
5254            geometry_extents,
5255            geometry_validation,
5256            camera_uniform,
5257        ) {
5258            return Err(RendererFrameError::InvalidGeometryTransform);
5259        }
5260
5261        let surface_acquire_started_at = Instant::now();
5262        let surface_texture = match self.surface.get_current_texture() {
5263            wgpu::CurrentSurfaceTexture::Success(texture)
5264            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
5265            wgpu::CurrentSurfaceTexture::Timeout => {
5266                return Ok(render_report(
5267                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
5268                    tessellation,
5269                    upload,
5270                    Duration::ZERO,
5271                    surface_acquire_started_at.elapsed(),
5272                    Duration::ZERO,
5273                    frame_started_at.elapsed(),
5274                    geometry_reused,
5275                    geometry_streamed,
5276                    tessellation_stats,
5277                ));
5278            }
5279            wgpu::CurrentSurfaceTexture::Occluded => {
5280                return Ok(render_report(
5281                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
5282                    tessellation,
5283                    upload,
5284                    Duration::ZERO,
5285                    surface_acquire_started_at.elapsed(),
5286                    Duration::ZERO,
5287                    frame_started_at.elapsed(),
5288                    geometry_reused,
5289                    geometry_streamed,
5290                    tessellation_stats,
5291                ));
5292            }
5293            wgpu::CurrentSurfaceTexture::Outdated => {
5294                let _ = self.resize(self.config.width, self.config.height);
5295                return Ok(render_report(
5296                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
5297                    tessellation,
5298                    upload,
5299                    Duration::ZERO,
5300                    surface_acquire_started_at.elapsed(),
5301                    Duration::ZERO,
5302                    frame_started_at.elapsed(),
5303                    geometry_reused,
5304                    geometry_streamed,
5305                    tessellation_stats,
5306                ));
5307            }
5308            wgpu::CurrentSurfaceTexture::Lost => {
5309                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
5310            }
5311            wgpu::CurrentSurfaceTexture::Validation => {
5312                return Err(RendererFrameError::Surface(
5313                    RendererSurfaceStatus::Validation,
5314                ));
5315            }
5316        };
5317        let surface_acquire = surface_acquire_started_at.elapsed();
5318        let vertex_upload_started_at = Instant::now();
5319        if let Some(vertices) = pending_vertex_upload
5320            && !vertices.is_empty()
5321        {
5322            self.queue
5323                .write_buffer(vertex_buffer, 0, bytemuck::cast_slice(vertices));
5324        }
5325        upload = upload.saturating_add(vertex_upload_started_at.elapsed());
5326        let camera_uniform_upload_started_at = Instant::now();
5327        self.queue.write_buffer(
5328            &self.camera_uniform_buffer,
5329            0,
5330            bytemuck::bytes_of(&camera_uniform),
5331        );
5332        let camera_uniform_upload = camera_uniform_upload_started_at.elapsed();
5333
5334        let encode_submit_present_started_at = Instant::now();
5335        let surface_view = surface_texture
5336            .texture
5337            .create_view(&wgpu::TextureViewDescriptor::default());
5338        let (view, resolve_target) = match &self.multisample_target {
5339            Some(target) => (&target.view, Some(&surface_view)),
5340            None => (&surface_view, None),
5341        };
5342
5343        let mut encoder = self
5344            .device
5345            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5346                label: Some("sim-engine render encoder"),
5347            });
5348
5349        {
5350            let color_attachment = wgpu::RenderPassColorAttachment {
5351                view,
5352                depth_slice: None,
5353                resolve_target,
5354                ops: wgpu::Operations {
5355                    load: wgpu::LoadOp::Clear(background.to_wgpu()),
5356                    store: wgpu::StoreOp::Store,
5357                },
5358            };
5359            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5360                label: Some("sim-engine render pass"),
5361                color_attachments: &[Some(color_attachment)],
5362                depth_stencil_attachment: None,
5363                timestamp_writes: None,
5364                occlusion_query_set: None,
5365                multiview_mask: None,
5366            });
5367
5368            if vertex_count > 0 {
5369                let pipeline = if uses_dynamic_pipeline {
5370                    &self.dynamic_pipeline
5371                } else {
5372                    &self.pipeline
5373                };
5374                pass.set_pipeline(pipeline);
5375                pass.set_bind_group(0, &self.camera_bind_group, &[]);
5376                pass.set_vertex_buffer(0, vertex_buffer.slice(..));
5377                for batch in draw_batches {
5378                    let scissor = match batch.screen_clip {
5379                        Some(screen_clip) => {
5380                            let Some(local_scissor) = screen_clip_to_scissor(
5381                                screen_clip,
5382                                viewport,
5383                                self.scale_factor as f32,
5384                            ) else {
5385                                continue;
5386                            };
5387                            let Some(scissor) = offset_scissor(local_scissor, viewport_scissor)
5388                            else {
5389                                continue;
5390                            };
5391                            scissor
5392                        }
5393                        None => viewport_scissor,
5394                    };
5395                    pass.set_scissor_rect(scissor.x, scissor.y, scissor.width, scissor.height);
5396                    pass.draw(batch.vertex_range.clone(), 0..1);
5397                }
5398            }
5399        }
5400
5401        self.queue.submit([encoder.finish()]);
5402        self.notify_before_present();
5403        self.queue.present(surface_texture);
5404        let encode_submit_present = encode_submit_present_started_at.elapsed();
5405
5406        Ok(render_report(
5407            RenderStatus::Drawn,
5408            tessellation,
5409            upload,
5410            camera_uniform_upload,
5411            surface_acquire,
5412            encode_submit_present,
5413            frame_started_at.elapsed(),
5414            geometry_reused,
5415            geometry_streamed,
5416            tessellation_stats,
5417        ))
5418    }
5419
5420    #[allow(clippy::too_many_arguments)]
5421    fn draw_scalar_field_texture(
5422        &mut self,
5423        texture: &ScalarFieldTexture,
5424        color_map: &ColorMap,
5425        minimum: f32,
5426        value_extent: f32,
5427        sampling: ScalarFieldSampling,
5428        background: Color,
5429        frame_started_at: Instant,
5430    ) -> Result<RenderReport, RendererFrameError> {
5431        let uniform = HeatmapUniform::new(
5432            minimum,
5433            value_extent,
5434            texture.width(),
5435            texture.height(),
5436            sampling,
5437        );
5438        let acquire_started_at = Instant::now();
5439        let surface_texture = match self.surface.get_current_texture() {
5440            wgpu::CurrentSurfaceTexture::Success(texture)
5441            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
5442            wgpu::CurrentSurfaceTexture::Timeout => {
5443                return Ok(render_report(
5444                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
5445                    Duration::ZERO,
5446                    Duration::ZERO,
5447                    Duration::ZERO,
5448                    acquire_started_at.elapsed(),
5449                    Duration::ZERO,
5450                    frame_started_at.elapsed(),
5451                    false,
5452                    true,
5453                    TessellationStats::default(),
5454                ));
5455            }
5456            wgpu::CurrentSurfaceTexture::Occluded => {
5457                return Ok(render_report(
5458                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
5459                    Duration::ZERO,
5460                    Duration::ZERO,
5461                    Duration::ZERO,
5462                    acquire_started_at.elapsed(),
5463                    Duration::ZERO,
5464                    frame_started_at.elapsed(),
5465                    false,
5466                    true,
5467                    TessellationStats::default(),
5468                ));
5469            }
5470            wgpu::CurrentSurfaceTexture::Outdated => {
5471                let _ = self.resize(self.config.width, self.config.height);
5472                return Ok(render_report(
5473                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
5474                    Duration::ZERO,
5475                    Duration::ZERO,
5476                    Duration::ZERO,
5477                    acquire_started_at.elapsed(),
5478                    Duration::ZERO,
5479                    frame_started_at.elapsed(),
5480                    false,
5481                    true,
5482                    TessellationStats::default(),
5483                ));
5484            }
5485            wgpu::CurrentSurfaceTexture::Lost => {
5486                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
5487            }
5488            wgpu::CurrentSurfaceTexture::Validation => {
5489                return Err(RendererFrameError::Surface(
5490                    RendererSurfaceStatus::Validation,
5491                ));
5492            }
5493        };
5494        let surface_acquire = acquire_started_at.elapsed();
5495        let upload_started_at = Instant::now();
5496        let color_map_view = self.color_map_view(color_map);
5497        let scalar_view = texture
5498            .texture
5499            .create_view(&wgpu::TextureViewDescriptor::default());
5500        self.queue.write_buffer(
5501            &self.heatmap_uniform_buffer,
5502            0,
5503            bytemuck::bytes_of(&uniform),
5504        );
5505        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5506            label: Some("sim-engine heatmap bind group"),
5507            layout: &self.heatmap_bind_group_layout,
5508            entries: &[
5509                wgpu::BindGroupEntry {
5510                    binding: 0,
5511                    resource: wgpu::BindingResource::TextureView(&scalar_view),
5512                },
5513                wgpu::BindGroupEntry {
5514                    binding: 1,
5515                    resource: wgpu::BindingResource::TextureView(&color_map_view),
5516                },
5517                wgpu::BindGroupEntry {
5518                    binding: 2,
5519                    resource: self.heatmap_uniform_buffer.as_entire_binding(),
5520                },
5521            ],
5522        });
5523        let upload = upload_started_at.elapsed();
5524        let encode_started_at = Instant::now();
5525        let surface_view = surface_texture
5526            .texture
5527            .create_view(&wgpu::TextureViewDescriptor::default());
5528        let (view, resolve_target) = match &self.multisample_target {
5529            Some(target) => (&target.view, Some(&surface_view)),
5530            None => (&surface_view, None),
5531        };
5532        let mut encoder = self
5533            .device
5534            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5535                label: Some("sim-engine heatmap encoder"),
5536            });
5537        {
5538            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5539                label: Some("sim-engine heatmap pass"),
5540                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5541                    view,
5542                    depth_slice: None,
5543                    resolve_target,
5544                    ops: wgpu::Operations {
5545                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
5546                        store: wgpu::StoreOp::Store,
5547                    },
5548                })],
5549                depth_stencil_attachment: None,
5550                timestamp_writes: None,
5551                occlusion_query_set: None,
5552                multiview_mask: None,
5553            });
5554            pass.set_pipeline(&self.heatmap_pipeline);
5555            pass.set_bind_group(0, &bind_group, &[]);
5556            pass.draw(0..6, 0..1);
5557        }
5558        self.queue.submit([encoder.finish()]);
5559        self.notify_before_present();
5560        self.queue.present(surface_texture);
5561        Ok(render_report(
5562            RenderStatus::Drawn,
5563            Duration::ZERO,
5564            upload,
5565            Duration::ZERO,
5566            surface_acquire,
5567            encode_started_at.elapsed(),
5568            frame_started_at.elapsed(),
5569            false,
5570            true,
5571            TessellationStats::default(),
5572        ))
5573    }
5574
5575    #[allow(clippy::too_many_arguments)]
5576    fn draw_scalar_field_texture_to_target(
5577        &mut self,
5578        target: &RenderTarget2d,
5579        texture: &ScalarFieldTexture,
5580        color_map: &ColorMap,
5581        minimum: f32,
5582        value_extent: f32,
5583        sampling: ScalarFieldSampling,
5584        background: Color,
5585        frame_started_at: Instant,
5586    ) -> RenderReport {
5587        let upload_started_at = Instant::now();
5588        let color_map_view = self.color_map_view(color_map);
5589        let scalar_view = texture
5590            .texture
5591            .create_view(&wgpu::TextureViewDescriptor::default());
5592        self.queue.write_buffer(
5593            &self.heatmap_uniform_buffer,
5594            0,
5595            bytemuck::bytes_of(&HeatmapUniform::new(
5596                minimum,
5597                value_extent,
5598                texture.width(),
5599                texture.height(),
5600                sampling,
5601            )),
5602        );
5603        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5604            label: Some("sim-engine target heatmap bind group"),
5605            layout: &self.heatmap_bind_group_layout,
5606            entries: &[
5607                wgpu::BindGroupEntry {
5608                    binding: 0,
5609                    resource: wgpu::BindingResource::TextureView(&scalar_view),
5610                },
5611                wgpu::BindGroupEntry {
5612                    binding: 1,
5613                    resource: wgpu::BindingResource::TextureView(&color_map_view),
5614                },
5615                wgpu::BindGroupEntry {
5616                    binding: 2,
5617                    resource: self.heatmap_uniform_buffer.as_entire_binding(),
5618                },
5619            ],
5620        });
5621        let upload = upload_started_at.elapsed();
5622        let encode_started_at = Instant::now();
5623        let mut encoder = self
5624            .device
5625            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5626                label: Some("sim-engine render-target heatmap encoder"),
5627            });
5628        {
5629            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5630                label: Some("sim-engine render-target heatmap pass"),
5631                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5632                    view: &target.view,
5633                    depth_slice: None,
5634                    resolve_target: None,
5635                    ops: wgpu::Operations {
5636                        load: wgpu::LoadOp::Clear(premultiplied_wgpu_color(background)),
5637                        store: wgpu::StoreOp::Store,
5638                    },
5639                })],
5640                depth_stencil_attachment: None,
5641                timestamp_writes: None,
5642                occlusion_query_set: None,
5643                multiview_mask: None,
5644            });
5645            pass.set_pipeline(&self.target_heatmap_pipeline);
5646            pass.set_bind_group(0, &bind_group, &[]);
5647            pass.draw(0..6, 0..1);
5648        }
5649        self.queue.submit([encoder.finish()]);
5650        render_report(
5651            RenderStatus::Drawn,
5652            Duration::ZERO,
5653            upload,
5654            Duration::ZERO,
5655            Duration::ZERO,
5656            encode_started_at.elapsed(),
5657            frame_started_at.elapsed(),
5658            false,
5659            true,
5660            TessellationStats::default(),
5661        )
5662    }
5663
5664    fn draw_composed_render_target(
5665        &mut self,
5666        target: &RenderTarget2d,
5667        blend_mode: BlendMode,
5668        opacity: f32,
5669        background: Color,
5670        frame_started_at: Instant,
5671    ) -> Result<RenderReport, RendererFrameError> {
5672        let acquire_started_at = Instant::now();
5673        let surface_texture = match self.surface.get_current_texture() {
5674            wgpu::CurrentSurfaceTexture::Success(texture)
5675            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
5676            wgpu::CurrentSurfaceTexture::Timeout => {
5677                return Ok(render_report(
5678                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
5679                    Duration::ZERO,
5680                    Duration::ZERO,
5681                    Duration::ZERO,
5682                    acquire_started_at.elapsed(),
5683                    Duration::ZERO,
5684                    frame_started_at.elapsed(),
5685                    false,
5686                    true,
5687                    TessellationStats::default(),
5688                ));
5689            }
5690            wgpu::CurrentSurfaceTexture::Occluded => {
5691                return Ok(render_report(
5692                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
5693                    Duration::ZERO,
5694                    Duration::ZERO,
5695                    Duration::ZERO,
5696                    acquire_started_at.elapsed(),
5697                    Duration::ZERO,
5698                    frame_started_at.elapsed(),
5699                    false,
5700                    true,
5701                    TessellationStats::default(),
5702                ));
5703            }
5704            wgpu::CurrentSurfaceTexture::Outdated => {
5705                let _ = self.resize(self.config.width, self.config.height);
5706                return Ok(render_report(
5707                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
5708                    Duration::ZERO,
5709                    Duration::ZERO,
5710                    Duration::ZERO,
5711                    acquire_started_at.elapsed(),
5712                    Duration::ZERO,
5713                    frame_started_at.elapsed(),
5714                    false,
5715                    true,
5716                    TessellationStats::default(),
5717                ));
5718            }
5719            wgpu::CurrentSurfaceTexture::Lost => {
5720                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
5721            }
5722            wgpu::CurrentSurfaceTexture::Validation => {
5723                return Err(RendererFrameError::Surface(
5724                    RendererSurfaceStatus::Validation,
5725                ));
5726            }
5727        };
5728        let surface_acquire = acquire_started_at.elapsed();
5729        let upload_started_at = Instant::now();
5730        self.queue.write_buffer(
5731            &self.composition_pipelines.uniform_buffer,
5732            0,
5733            bytemuck::bytes_of(&CompositeUniform::full_surface(opacity)),
5734        );
5735        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5736            label: Some("sim-engine composition bind group"),
5737            layout: &self.composition_pipelines.bind_group_layout,
5738            entries: &[
5739                wgpu::BindGroupEntry {
5740                    binding: 0,
5741                    resource: wgpu::BindingResource::TextureView(&target.view),
5742                },
5743                wgpu::BindGroupEntry {
5744                    binding: 1,
5745                    resource: self
5746                        .composition_pipelines
5747                        .uniform_buffer
5748                        .as_entire_binding(),
5749                },
5750            ],
5751        });
5752        let upload = upload_started_at.elapsed();
5753        let encode_started_at = Instant::now();
5754        let surface_view = surface_texture
5755            .texture
5756            .create_view(&wgpu::TextureViewDescriptor::default());
5757        let (view, resolve_target) = match &self.multisample_target {
5758            Some(multisample_target) => (&multisample_target.view, Some(&surface_view)),
5759            None => (&surface_view, None),
5760        };
5761        let mut encoder = self
5762            .device
5763            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5764                label: Some("sim-engine composition encoder"),
5765            });
5766        {
5767            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5768                label: Some("sim-engine composition pass"),
5769                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5770                    view,
5771                    depth_slice: None,
5772                    resolve_target,
5773                    ops: wgpu::Operations {
5774                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
5775                        store: wgpu::StoreOp::Store,
5776                    },
5777                })],
5778                depth_stencil_attachment: None,
5779                timestamp_writes: None,
5780                occlusion_query_set: None,
5781                multiview_mask: None,
5782            });
5783            pass.set_pipeline(self.composition_pipelines.pipeline(blend_mode));
5784            pass.set_bind_group(0, &bind_group, &[]);
5785            pass.draw(0..6, 0..1);
5786        }
5787        self.queue.submit([encoder.finish()]);
5788        self.notify_before_present();
5789        self.queue.present(surface_texture);
5790        Ok(render_report(
5791            RenderStatus::Drawn,
5792            Duration::ZERO,
5793            upload,
5794            Duration::ZERO,
5795            surface_acquire,
5796            encode_started_at.elapsed(),
5797            frame_started_at.elapsed(),
5798            false,
5799            true,
5800            TessellationStats::default(),
5801        ))
5802    }
5803
5804    #[allow(clippy::too_many_arguments)]
5805    fn draw_trail_accumulation(
5806        &mut self,
5807        trails: &mut TrailBuffer2d,
5808        source: &RenderTarget2d,
5809        retention: f32,
5810        source_opacity: f32,
5811        source_blend: BlendMode,
5812        frame_started_at: Instant,
5813    ) -> RenderReport {
5814        let upload_started_at = Instant::now();
5815        self.queue.write_buffer(
5816            &self.target_composition_pipelines.secondary_uniform_buffer,
5817            0,
5818            bytemuck::bytes_of(&CompositeUniform::full_surface(retention)),
5819        );
5820        self.queue.write_buffer(
5821            &self.target_composition_pipelines.uniform_buffer,
5822            0,
5823            bytemuck::bytes_of(&CompositeUniform::full_surface(source_opacity)),
5824        );
5825        let history_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5826            label: Some("sim-engine trail history bind group"),
5827            layout: &self.target_composition_pipelines.bind_group_layout,
5828            entries: &[
5829                wgpu::BindGroupEntry {
5830                    binding: 0,
5831                    resource: wgpu::BindingResource::TextureView(&trails.front.view),
5832                },
5833                wgpu::BindGroupEntry {
5834                    binding: 1,
5835                    resource: self
5836                        .target_composition_pipelines
5837                        .secondary_uniform_buffer
5838                        .as_entire_binding(),
5839                },
5840            ],
5841        });
5842        let source_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5843            label: Some("sim-engine trail source bind group"),
5844            layout: &self.target_composition_pipelines.bind_group_layout,
5845            entries: &[
5846                wgpu::BindGroupEntry {
5847                    binding: 0,
5848                    resource: wgpu::BindingResource::TextureView(&source.view),
5849                },
5850                wgpu::BindGroupEntry {
5851                    binding: 1,
5852                    resource: self
5853                        .target_composition_pipelines
5854                        .uniform_buffer
5855                        .as_entire_binding(),
5856                },
5857            ],
5858        });
5859        let upload = upload_started_at.elapsed();
5860        let encode_started_at = Instant::now();
5861        let mut encoder = self
5862            .device
5863            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5864                label: Some("sim-engine trail accumulation encoder"),
5865            });
5866        {
5867            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5868                label: Some("sim-engine trail history pass"),
5869                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5870                    view: &trails.back.view,
5871                    depth_slice: None,
5872                    resolve_target: None,
5873                    ops: wgpu::Operations {
5874                        load: wgpu::LoadOp::Clear(Color::rgba(0.0, 0.0, 0.0, 0.0).to_wgpu()),
5875                        store: wgpu::StoreOp::Store,
5876                    },
5877                })],
5878                depth_stencil_attachment: None,
5879                timestamp_writes: None,
5880                occlusion_query_set: None,
5881                multiview_mask: None,
5882            });
5883            pass.set_pipeline(&self.target_composition_pipelines.alpha);
5884            pass.set_bind_group(0, &history_bind_group, &[]);
5885            pass.draw(0..6, 0..1);
5886        }
5887        {
5888            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5889                label: Some("sim-engine trail source pass"),
5890                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5891                    view: &trails.back.view,
5892                    depth_slice: None,
5893                    resolve_target: None,
5894                    ops: wgpu::Operations {
5895                        load: wgpu::LoadOp::Load,
5896                        store: wgpu::StoreOp::Store,
5897                    },
5898                })],
5899                depth_stencil_attachment: None,
5900                timestamp_writes: None,
5901                occlusion_query_set: None,
5902                multiview_mask: None,
5903            });
5904            pass.set_pipeline(self.target_composition_pipelines.pipeline(source_blend));
5905            pass.set_bind_group(0, &source_bind_group, &[]);
5906            pass.draw(0..6, 0..1);
5907        }
5908        self.queue.submit([encoder.finish()]);
5909        std::mem::swap(&mut trails.front, &mut trails.back);
5910        render_report(
5911            RenderStatus::Drawn,
5912            Duration::ZERO,
5913            upload,
5914            Duration::ZERO,
5915            Duration::ZERO,
5916            encode_started_at.elapsed(),
5917            frame_started_at.elapsed(),
5918            false,
5919            true,
5920            TessellationStats::default(),
5921        )
5922    }
5923
5924    fn draw_clear_trail_buffer(
5925        &self,
5926        trails: &TrailBuffer2d,
5927        color: Color,
5928        frame_started_at: Instant,
5929    ) -> RenderReport {
5930        let encode_started_at = Instant::now();
5931        let mut encoder = self
5932            .device
5933            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
5934                label: Some("sim-engine trail clear encoder"),
5935            });
5936        for view in [&trails.front.view, &trails.back.view] {
5937            let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
5938                label: Some("sim-engine trail clear pass"),
5939                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
5940                    view,
5941                    depth_slice: None,
5942                    resolve_target: None,
5943                    ops: wgpu::Operations {
5944                        load: wgpu::LoadOp::Clear(premultiplied_wgpu_color(color)),
5945                        store: wgpu::StoreOp::Store,
5946                    },
5947                })],
5948                depth_stencil_attachment: None,
5949                timestamp_writes: None,
5950                occlusion_query_set: None,
5951                multiview_mask: None,
5952            });
5953        }
5954        self.queue.submit([encoder.finish()]);
5955        render_report(
5956            RenderStatus::Drawn,
5957            Duration::ZERO,
5958            Duration::ZERO,
5959            Duration::ZERO,
5960            Duration::ZERO,
5961            encode_started_at.elapsed(),
5962            frame_started_at.elapsed(),
5963            false,
5964            true,
5965            TessellationStats::default(),
5966        )
5967    }
5968
5969    fn prepare_particle_draw(
5970        &self,
5971        field: &mut ParticleField2d,
5972        camera: Camera2d,
5973    ) -> Result<ParticleDrawPreparation, RendererFrameError> {
5974        let (logical_width, logical_height) = self.logical_size();
5975        let viewport = LogicalViewport::new(logical_width, logical_height)
5976            .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
5977        let Some(camera_uniform) = CameraUniform::new(camera, viewport) else {
5978            return Err(RendererFrameError::InvalidGeometryTransform);
5979        };
5980        let instance_count = field.instances.len();
5981        let visibility_checked = instance_count.min(field.budget.max_visibility_checks_per_frame);
5982        if visibility_checked < instance_count {
5983            field.visible_instances.clear();
5984            validate_particle_staging_capacity(&field.visible_instances, visibility_checked)?;
5985            for candidate_index in 0..visibility_checked {
5986                let source_index =
5987                    uniformly_sampled_index(candidate_index, instance_count, visibility_checked);
5988                let instance = field.instances[source_index];
5989                let Some(intersects) =
5990                    instance.validated_viewport_intersection(camera_uniform, viewport)
5991                else {
5992                    return Err(RendererFrameError::InvalidGeometryTransform);
5993                };
5994                if intersects {
5995                    field.visible_instances.push(instance);
5996                }
5997            }
5998            let visible_count = field.visible_instances.len();
5999            let selected_count = visible_count.min(field.budget.instance_limit());
6000            if selected_count < visible_count {
6001                let mut visible_index = 0;
6002                field.visible_instances.retain(|_| {
6003                    let selected = particle_visible_index_is_selected(
6004                        visible_index,
6005                        visible_count,
6006                        selected_count,
6007                    );
6008                    visible_index += 1;
6009                    selected
6010                });
6011            }
6012            let statistics = particle_statistics_with_budget(
6013                instance_count,
6014                visibility_checked,
6015                visible_count,
6016                selected_count,
6017                0,
6018            );
6019            return Ok(ParticleDrawPreparation {
6020                camera_uniform,
6021                visible_count: selected_count,
6022                statistics,
6023            });
6024        }
6025
6026        let visible_count = visible_particle_count(&field.instances, camera_uniform, viewport)?;
6027        let selected_count = visible_count.min(field.budget.instance_limit());
6028        let statistics = particle_statistics_with_budget(
6029            instance_count,
6030            instance_count,
6031            visible_count,
6032            selected_count,
6033            0,
6034        );
6035        if selected_count == field.instances.len() {
6036            field.visible_instances.clear();
6037        } else {
6038            field.visible_instances.clear();
6039            validate_particle_staging_capacity(&field.visible_instances, selected_count)?;
6040            let mut visible_index = 0;
6041            for instance in field.instances.iter().copied() {
6042                if !instance.intersects_viewport(camera_uniform, viewport) {
6043                    continue;
6044                }
6045                let selected_index = field.visible_instances.len();
6046                if selected_index < selected_count
6047                    && particle_visible_index_is_selected(
6048                        visible_index,
6049                        visible_count,
6050                        selected_count,
6051                    )
6052                {
6053                    field.visible_instances.push(instance);
6054                }
6055                visible_index += 1;
6056            }
6057        }
6058        Ok(ParticleDrawPreparation {
6059            camera_uniform,
6060            visible_count: selected_count,
6061            statistics,
6062        })
6063    }
6064
6065    fn upload_particle_draw(
6066        &self,
6067        field: &ParticleField2d,
6068        preparation: ParticleDrawPreparation,
6069    ) -> (Duration, Duration) {
6070        let visible_instances = if field.visible_instances.is_empty()
6071            && preparation.visible_count == field.instances.len()
6072        {
6073            field.instances.as_slice()
6074        } else {
6075            field.visible_instances.as_slice()
6076        };
6077        let upload_started_at = Instant::now();
6078        if !visible_instances.is_empty() {
6079            self.queue.write_buffer(
6080                &field.instance_buffer,
6081                0,
6082                bytemuck::cast_slice(visible_instances),
6083            );
6084        }
6085        let upload = upload_started_at.elapsed();
6086        let camera_uniform_upload_started_at = Instant::now();
6087        self.queue.write_buffer(
6088            &self.camera_uniform_buffer,
6089            0,
6090            bytemuck::bytes_of(&preparation.camera_uniform),
6091        );
6092        let camera_uniform_upload = camera_uniform_upload_started_at.elapsed();
6093        (upload, camera_uniform_upload)
6094    }
6095
6096    fn draw_particle_field(
6097        &mut self,
6098        background: Color,
6099        field: &mut ParticleField2d,
6100        camera: Camera2d,
6101        frame_started_at: Instant,
6102    ) -> Result<RenderReport, RendererFrameError> {
6103        let preparation_started_at = Instant::now();
6104        let preparation = self.prepare_particle_draw(field, camera)?;
6105        let preparation_duration = preparation_started_at.elapsed();
6106
6107        let surface_acquire_started_at = Instant::now();
6108        let surface_texture = match self.surface.get_current_texture() {
6109            wgpu::CurrentSurfaceTexture::Success(texture)
6110            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
6111            wgpu::CurrentSurfaceTexture::Timeout => {
6112                field.statistics = preparation.statistics;
6113                return Ok(render_report(
6114                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
6115                    preparation_duration,
6116                    Duration::ZERO,
6117                    Duration::ZERO,
6118                    surface_acquire_started_at.elapsed(),
6119                    Duration::ZERO,
6120                    frame_started_at.elapsed(),
6121                    false,
6122                    true,
6123                    TessellationStats::default(),
6124                ));
6125            }
6126            wgpu::CurrentSurfaceTexture::Occluded => {
6127                field.statistics = preparation.statistics;
6128                return Ok(render_report(
6129                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
6130                    preparation_duration,
6131                    Duration::ZERO,
6132                    Duration::ZERO,
6133                    surface_acquire_started_at.elapsed(),
6134                    Duration::ZERO,
6135                    frame_started_at.elapsed(),
6136                    false,
6137                    true,
6138                    TessellationStats::default(),
6139                ));
6140            }
6141            wgpu::CurrentSurfaceTexture::Outdated => {
6142                let _ = self.resize(self.config.width, self.config.height);
6143                field.statistics = preparation.statistics;
6144                return Ok(render_report(
6145                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
6146                    preparation_duration,
6147                    Duration::ZERO,
6148                    Duration::ZERO,
6149                    surface_acquire_started_at.elapsed(),
6150                    Duration::ZERO,
6151                    frame_started_at.elapsed(),
6152                    false,
6153                    true,
6154                    TessellationStats::default(),
6155                ));
6156            }
6157            wgpu::CurrentSurfaceTexture::Lost => {
6158                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
6159            }
6160            wgpu::CurrentSurfaceTexture::Validation => {
6161                return Err(RendererFrameError::Surface(
6162                    RendererSurfaceStatus::Validation,
6163                ));
6164            }
6165        };
6166        let surface_acquire = surface_acquire_started_at.elapsed();
6167        let (upload, camera_uniform_upload) = self.upload_particle_draw(field, preparation);
6168        let encode_submit_present_started_at = Instant::now();
6169        let surface_view = surface_texture
6170            .texture
6171            .create_view(&wgpu::TextureViewDescriptor::default());
6172        let (view, resolve_target) = match &self.multisample_target {
6173            Some(target) => (&target.view, Some(&surface_view)),
6174            None => (&surface_view, None),
6175        };
6176        let mut encoder = self
6177            .device
6178            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
6179                label: Some("sim-engine particle render encoder"),
6180            });
6181        {
6182            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
6183                label: Some("sim-engine particle render pass"),
6184                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
6185                    view,
6186                    depth_slice: None,
6187                    resolve_target,
6188                    ops: wgpu::Operations {
6189                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
6190                        store: wgpu::StoreOp::Store,
6191                    },
6192                })],
6193                depth_stencil_attachment: None,
6194                timestamp_writes: None,
6195                occlusion_query_set: None,
6196                multiview_mask: None,
6197            });
6198            if preparation.visible_count > 0 {
6199                pass.set_pipeline(&self.particle_pipeline);
6200                pass.set_bind_group(0, &self.camera_bind_group, &[]);
6201                pass.set_vertex_buffer(0, self.particle_unit_buffer.slice(..));
6202                pass.set_vertex_buffer(1, field.instance_buffer.slice(..));
6203                pass.draw(0..6, 0..preparation.visible_count as u32);
6204            }
6205        }
6206        self.queue.submit([encoder.finish()]);
6207        self.notify_before_present();
6208        self.queue.present(surface_texture);
6209        field.statistics = ParticleStatistics {
6210            rendered: preparation.visible_count,
6211            ..preparation.statistics
6212        };
6213        Ok(render_report(
6214            RenderStatus::Drawn,
6215            preparation_duration,
6216            upload,
6217            camera_uniform_upload,
6218            surface_acquire,
6219            encode_submit_present_started_at.elapsed(),
6220            frame_started_at.elapsed(),
6221            false,
6222            true,
6223            TessellationStats::default(),
6224        ))
6225    }
6226
6227    fn draw_particle_field_to_target(
6228        &self,
6229        target: &RenderTarget2d,
6230        field: &mut ParticleField2d,
6231        camera: Camera2d,
6232        load: RenderTargetLoad,
6233        frame_started_at: Instant,
6234    ) -> Result<RenderReport, RendererFrameError> {
6235        let preparation_started_at = Instant::now();
6236        let preparation = self.prepare_particle_draw(field, camera)?;
6237        let preparation_duration = preparation_started_at.elapsed();
6238        let (upload, camera_uniform_upload) = self.upload_particle_draw(field, preparation);
6239        let encode_started_at = Instant::now();
6240        let mut encoder = self
6241            .device
6242            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
6243                label: Some("sim-engine target particle encoder"),
6244            });
6245        {
6246            let load = match load {
6247                RenderTargetLoad::Load => wgpu::LoadOp::Load,
6248                RenderTargetLoad::Clear(color) => {
6249                    wgpu::LoadOp::Clear(premultiplied_wgpu_color(color))
6250                }
6251            };
6252            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
6253                label: Some("sim-engine target particle pass"),
6254                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
6255                    view: &target.view,
6256                    depth_slice: None,
6257                    resolve_target: None,
6258                    ops: wgpu::Operations {
6259                        load,
6260                        store: wgpu::StoreOp::Store,
6261                    },
6262                })],
6263                depth_stencil_attachment: None,
6264                timestamp_writes: None,
6265                occlusion_query_set: None,
6266                multiview_mask: None,
6267            });
6268            if preparation.visible_count > 0 {
6269                pass.set_pipeline(&self.target_particle_pipeline);
6270                pass.set_bind_group(0, &self.camera_bind_group, &[]);
6271                pass.set_vertex_buffer(0, self.particle_unit_buffer.slice(..));
6272                pass.set_vertex_buffer(1, field.instance_buffer.slice(..));
6273                pass.draw(0..6, 0..preparation.visible_count as u32);
6274            }
6275        }
6276        self.queue.submit([encoder.finish()]);
6277        field.statistics = ParticleStatistics {
6278            rendered: preparation.visible_count,
6279            ..preparation.statistics
6280        };
6281        Ok(render_report(
6282            RenderStatus::Drawn,
6283            preparation_duration,
6284            upload,
6285            camera_uniform_upload,
6286            Duration::ZERO,
6287            encode_started_at.elapsed(),
6288            frame_started_at.elapsed(),
6289            false,
6290            true,
6291            TessellationStats::default(),
6292        ))
6293    }
6294
6295    fn ensure_vertex_capacity(&mut self, vertex_count: usize) -> Result<(), RendererFrameError> {
6296        if vertex_count <= self.vertex_capacity {
6297            return Ok(());
6298        }
6299
6300        self.vertex_capacity = dynamic_vertex_capacity(vertex_count)
6301            .filter(|capacity| buffer_capacity_fits::<Vertex>(&self.device, *capacity))
6302            .ok_or(RendererFrameError::GeometryCapacityTooLarge)?;
6303        self.vertex_buffer = Arc::new(create_vertex_buffer(&self.device, self.vertex_capacity));
6304        Ok(())
6305    }
6306
6307    fn validate_dynamic_mesh(&self, mesh: &DynamicMesh2d) -> Result<(), DynamicMeshError> {
6308        prepared_scene_belongs_to(&self.renderer_identity, &mesh.renderer_identity)
6309            .then_some(())
6310            .ok_or(DynamicMeshError::RendererMismatch)
6311    }
6312
6313    fn validate_particle_field(&self, field: &ParticleField2d) -> Result<(), ParticleFieldError> {
6314        prepared_scene_belongs_to(&self.renderer_identity, &field.renderer_identity)
6315            .then_some(())
6316            .ok_or(ParticleFieldError::RendererMismatch)
6317    }
6318
6319    fn validate_scalar_field_texture(
6320        &self,
6321        texture: &ScalarFieldTexture,
6322    ) -> Result<(), ScalarFieldTextureError> {
6323        prepared_scene_belongs_to(&self.renderer_identity, &texture.renderer_identity)
6324            .then_some(())
6325            .ok_or(ScalarFieldTextureError::RendererMismatch)
6326    }
6327
6328    fn color_map_view(&mut self, color_map: &ColorMap) -> wgpu::TextureView {
6329        let lut = color_map_lut(color_map);
6330        if let Some(cached) = self
6331            .color_map_cache
6332            .as_ref()
6333            .filter(|cached| cached.lut == lut)
6334        {
6335            return cached.view.clone();
6336        }
6337        let cached = create_cached_color_map(&self.device, &self.queue, lut);
6338        let view = cached.view.clone();
6339        self.color_map_cache = Some(cached);
6340        view
6341    }
6342
6343    fn validate_render_target(&self, target: &RenderTarget2d) -> Result<(), RenderTargetError> {
6344        prepared_scene_belongs_to(&self.renderer_identity, &target.renderer_identity)
6345            .then_some(())
6346            .ok_or(RenderTargetError::RendererMismatch)
6347    }
6348
6349    fn validate_trail_buffer(&self, trails: &TrailBuffer2d) -> Result<(), RenderTargetError> {
6350        prepared_scene_belongs_to(&self.renderer_identity, &trails.renderer_identity)
6351            .then_some(())
6352            .ok_or(RenderTargetError::RendererMismatch)
6353    }
6354}
6355
6356fn invoke_pre_present_notify(
6357    present_mode: RendererSurfacePresentMode,
6358    notify: Option<&(dyn Fn() + Send + Sync)>,
6359) {
6360    if present_mode.is_refresh_synchronized()
6361        && let Some(notify) = notify
6362    {
6363        notify();
6364    }
6365}
6366
6367fn prepared_scene_belongs_to(renderer_identity: &Arc<()>, scene_identity: &Arc<()>) -> bool {
6368    Arc::ptr_eq(renderer_identity, scene_identity)
6369}
6370
6371fn render_target_allocation_bytes(
6372    format: wgpu::TextureFormat,
6373    width: u32,
6374    height: u32,
6375) -> Option<usize> {
6376    let bytes_per_texel = u64::from(format.block_copy_size(None)?);
6377    let byte_count = u64::from(width)
6378        .checked_mul(u64::from(height))?
6379        .checked_mul(bytes_per_texel)?;
6380    usize::try_from(byte_count).ok()
6381}
6382
6383fn dynamic_vertices_to_gpu(
6384    vertices: &[DynamicVertex2d],
6385) -> Result<Vec<DynamicGpu>, DynamicMeshError> {
6386    validate_dynamic_vertices(vertices)?;
6387    let requested_bytes = dynamic_mesh_bytes(vertices.len())?;
6388    let mut converted = Vec::new();
6389    converted
6390        .try_reserve_exact(vertices.len())
6391        .map_err(|_| DynamicMeshError::AllocationFailed { requested_bytes })?;
6392    converted.extend(vertices.iter().copied().map(dynamic_vertex_to_gpu));
6393    Ok(converted)
6394}
6395
6396fn replace_dynamic_mesh_resources(
6397    device: &wgpu::Device,
6398    queue: &wgpu::Queue,
6399    mesh: &mut DynamicMesh2d,
6400    vertices: &[DynamicVertex2d],
6401) -> Result<DynamicMeshUpdateReport, DynamicMeshError> {
6402    let update_started_at = Instant::now();
6403    validate_dynamic_vertices(vertices)?;
6404    if let Some(budget) = mesh.budget {
6405        validate_dynamic_mesh_budget(budget, vertices.len())?;
6406    }
6407    let reallocated = vertices.len() > mesh.vertex_capacity;
6408    let replacement_capacity = if reallocated {
6409        let capacity = dynamic_vertex_capacity(vertices.len())
6410            .filter(|capacity| buffer_capacity_fits::<DynamicGpu>(device, *capacity))
6411            .ok_or(DynamicMeshError::CapacityTooLarge)?;
6412        Some(capacity)
6413    } else {
6414        None
6415    };
6416    let replacement_vertices = dynamic_vertices_to_gpu(vertices)?;
6417    if let Some(budget) = mesh.budget {
6418        validate_dynamic_retained_capacity(budget, &replacement_vertices)?;
6419    }
6420    let replacement = if let Some(capacity) = replacement_capacity {
6421        let buffer = Arc::new(create_dynamic_vertex_buffer(device, capacity));
6422        Some((buffer, capacity))
6423    } else {
6424        None
6425    };
6426    let upload_buffer = replacement
6427        .as_ref()
6428        .map_or(mesh.vertex_buffer.as_ref(), |(buffer, _)| buffer.as_ref());
6429    if !replacement_vertices.is_empty() {
6430        queue.write_buffer(
6431            upload_buffer,
6432            0,
6433            bytemuck::cast_slice(&replacement_vertices),
6434        );
6435        submit_pending_uploads(queue);
6436    }
6437    if let Some((buffer, capacity)) = replacement {
6438        mesh.vertex_buffer = buffer;
6439        mesh.vertex_capacity = capacity;
6440    }
6441    mesh.geometry_extents = GeometryExtents::from_dynamic_vertices(&replacement_vertices);
6442    mesh.vertices = replacement_vertices;
6443    mesh.geometry_validation_cache.clear();
6444    Ok(DynamicMeshUpdateReport {
6445        vertex_count: mesh.vertices.len(),
6446        upload: update_started_at.elapsed(),
6447        reallocated,
6448    })
6449}
6450
6451fn dynamic_mesh_bytes(vertex_count: usize) -> Result<usize, DynamicMeshError> {
6452    vertex_count
6453        .checked_mul(std::mem::size_of::<DynamicGpu>())
6454        .ok_or(DynamicMeshError::CapacityTooLarge)
6455}
6456
6457fn validate_dynamic_mesh_budget(
6458    budget: DynamicMeshBudget,
6459    vertex_count: usize,
6460) -> Result<(), DynamicMeshError> {
6461    if u32::try_from(vertex_count).is_err() {
6462        return Err(DynamicMeshError::CapacityTooLarge);
6463    }
6464    if vertex_count > budget.max_vertices {
6465        return Err(DynamicMeshError::BudgetExceeded {
6466            resource: DynamicMeshBudgetResource::Vertices,
6467            limit: budget.max_vertices,
6468            actual: vertex_count,
6469        });
6470    }
6471    let bytes = dynamic_mesh_bytes(vertex_count)?;
6472    if bytes > budget.max_retained_bytes {
6473        return Err(DynamicMeshError::BudgetExceeded {
6474            resource: DynamicMeshBudgetResource::RetainedBytes,
6475            limit: budget.max_retained_bytes,
6476            actual: bytes,
6477        });
6478    }
6479    if bytes > budget.max_upload_bytes {
6480        return Err(DynamicMeshError::BudgetExceeded {
6481            resource: DynamicMeshBudgetResource::UploadBytes,
6482            limit: budget.max_upload_bytes,
6483            actual: bytes,
6484        });
6485    }
6486    Ok(())
6487}
6488
6489fn validate_dynamic_retained_capacity(
6490    budget: DynamicMeshBudget,
6491    vertices: &Vec<DynamicGpu>,
6492) -> Result<(), DynamicMeshError> {
6493    let actual = vertices
6494        .capacity()
6495        .checked_mul(std::mem::size_of::<DynamicGpu>())
6496        .ok_or(DynamicMeshError::CapacityTooLarge)?;
6497    if actual > budget.max_retained_bytes {
6498        return Err(DynamicMeshError::BudgetExceeded {
6499            resource: DynamicMeshBudgetResource::RetainedBytes,
6500            limit: budget.max_retained_bytes,
6501            actual,
6502        });
6503    }
6504    Ok(())
6505}
6506
6507fn validate_dynamic_vertices(vertices: &[DynamicVertex2d]) -> Result<(), DynamicMeshError> {
6508    if u32::try_from(vertices.len()).is_err() {
6509        return Err(DynamicMeshError::CapacityTooLarge);
6510    }
6511    if !vertices.len().is_multiple_of(3) {
6512        return Err(DynamicMeshError::InvalidVertexCount);
6513    }
6514    if vertices.iter().any(|vertex| {
6515        ![
6516            vertex.world_position.x,
6517            vertex.world_position.y,
6518            vertex.depth,
6519        ]
6520        .into_iter()
6521        .all(is_portable_shader_source)
6522    }) {
6523        return Err(DynamicMeshError::InvalidVertex);
6524    }
6525    // Private fields and the only public constructor make finiteness an
6526    // invariant of DynamicVertex2d. Keep the assertion in development without
6527    // rescanning an already-validated high-volume stream in release builds.
6528    debug_assert!(vertices.iter().all(|vertex| {
6529        vertex.world_position.is_finite()
6530            && vertex.depth.is_finite()
6531            && vertex.color.is_normalized()
6532    }));
6533    Ok(())
6534}
6535
6536fn dynamic_vertex_to_gpu(vertex: DynamicVertex2d) -> DynamicGpu {
6537    DynamicGpu {
6538        world_position: [vertex.world_position.x, vertex.world_position.y],
6539        depth: vertex.depth,
6540        color: vertex.color.to_array(),
6541    }
6542}
6543
6544fn dynamic_vertex_capacity(vertex_count: usize) -> Option<usize> {
6545    vertex_count.max(1).checked_next_power_of_two()
6546}
6547
6548fn particle_instances_to_gpu(
6549    instances: &[ParticleInstance2d],
6550) -> Result<Vec<ParticleGpu>, ParticleFieldError> {
6551    if u32::try_from(instances.len()).is_err() {
6552        return Err(ParticleFieldError::CapacityTooLarge);
6553    }
6554    let requested_bytes = instances
6555        .len()
6556        .checked_mul(std::mem::size_of::<ParticleGpu>())
6557        .ok_or(ParticleFieldError::CapacityTooLarge)?;
6558    if instances.iter().copied().any(|instance| {
6559        let world_position = instance.world_position();
6560        let radius = instance.radius();
6561        let color = instance.color();
6562        let depth = instance.depth();
6563        ![world_position.x, world_position.y, radius, depth]
6564            .into_iter()
6565            .all(is_portable_shader_source)
6566            || radius <= 0.0
6567            || !color.is_normalized()
6568    }) {
6569        return Err(ParticleFieldError::InvalidInstance);
6570    }
6571    let mut output = Vec::new();
6572    output
6573        .try_reserve_exact(instances.len())
6574        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
6575    output.extend(instances.iter().copied().map(|instance| {
6576        let world_position = instance.world_position();
6577        ParticleGpu {
6578            world_position: [world_position.x, world_position.y],
6579            depth: instance.depth(),
6580            radius: instance.radius(),
6581            color: instance.color().to_array(),
6582        }
6583    }));
6584    Ok(output)
6585}
6586
6587fn particle_retained_bytes(instance_count: usize) -> Option<usize> {
6588    instance_count.checked_mul(std::mem::size_of::<ParticleGpu>())
6589}
6590
6591fn validate_particle_retained_count(
6592    instance_count: usize,
6593    budget: ParticleRenderBudget,
6594) -> Result<(), ParticleFieldError> {
6595    let staging_count = particle_staging_target(instance_count, budget);
6596    let retained_count = instance_count
6597        .checked_add(staging_count)
6598        .ok_or(ParticleFieldError::CapacityTooLarge)?;
6599    let actual =
6600        particle_retained_bytes(retained_count).ok_or(ParticleFieldError::CapacityTooLarge)?;
6601    if actual > budget.max_retained_bytes {
6602        return Err(ParticleFieldError::RetainedBudgetExceeded {
6603            limit: budget.max_retained_bytes,
6604            actual,
6605        });
6606    }
6607    Ok(())
6608}
6609
6610fn validate_particle_retained_capacities(
6611    instance_capacity: usize,
6612    staging_capacity: usize,
6613    budget: ParticleRenderBudget,
6614) -> Result<(), ParticleFieldError> {
6615    let retained_capacity = instance_capacity
6616        .checked_add(staging_capacity)
6617        .ok_or(ParticleFieldError::CapacityTooLarge)?;
6618    let actual =
6619        particle_retained_bytes(retained_capacity).ok_or(ParticleFieldError::CapacityTooLarge)?;
6620    if actual > budget.max_retained_bytes {
6621        return Err(ParticleFieldError::RetainedBudgetExceeded {
6622            limit: budget.max_retained_bytes,
6623            actual,
6624        });
6625    }
6626    Ok(())
6627}
6628
6629fn compact_particle_instances(
6630    source: &[ParticleGpu],
6631    current_capacity: usize,
6632    staging_capacity: usize,
6633    budget: ParticleRenderBudget,
6634) -> Result<Option<Vec<ParticleGpu>>, ParticleFieldError> {
6635    validate_particle_retained_count(source.len(), budget)?;
6636    if validate_particle_retained_capacities(current_capacity, staging_capacity, budget).is_ok() {
6637        return Ok(None);
6638    }
6639    let requested_bytes =
6640        particle_retained_bytes(source.len()).ok_or(ParticleFieldError::CapacityTooLarge)?;
6641    let mut compact = Vec::new();
6642    compact
6643        .try_reserve_exact(source.len())
6644        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
6645    compact.extend_from_slice(source);
6646    validate_particle_retained_capacities(compact.capacity(), staging_capacity, budget)?;
6647    Ok(Some(compact))
6648}
6649
6650fn particle_instance_capacity(instance_count: usize) -> Option<usize> {
6651    instance_count.max(1).checked_next_power_of_two()
6652}
6653
6654fn particle_budgeted_capacity(
6655    instance_count: usize,
6656    budget: ParticleRenderBudget,
6657) -> Option<usize> {
6658    let limit = budget.instance_limit();
6659    let required = instance_count.min(limit).max(1);
6660    particle_instance_capacity(required).map(|capacity| capacity.min(limit))
6661}
6662
6663fn allocate_particle_staging(
6664    instance_count: usize,
6665    budget: ParticleRenderBudget,
6666) -> Result<Vec<ParticleGpu>, ParticleFieldError> {
6667    let target = particle_staging_target(instance_count, budget);
6668    let requested_bytes = target
6669        .checked_mul(std::mem::size_of::<ParticleGpu>())
6670        .ok_or(ParticleFieldError::CapacityTooLarge)?;
6671    let mut staging = Vec::new();
6672    staging
6673        .try_reserve_exact(target)
6674        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
6675    Ok(staging)
6676}
6677
6678fn particle_staging_target(instance_count: usize, budget: ParticleRenderBudget) -> usize {
6679    let visibility_checked = instance_count.min(budget.max_visibility_checks_per_frame);
6680    if visibility_checked < instance_count {
6681        visibility_checked
6682    } else {
6683        instance_count.min(budget.instance_limit())
6684    }
6685}
6686
6687fn buffer_allocation_bytes<T>(capacity: usize) -> Option<u64> {
6688    u64::try_from(capacity)
6689        .ok()?
6690        .checked_mul(std::mem::size_of::<T>() as u64)
6691}
6692
6693fn buffer_capacity_fits<T>(device: &wgpu::Device, capacity: usize) -> bool {
6694    buffer_allocation_bytes::<T>(capacity)
6695        .is_some_and(|bytes| bytes <= device.limits().max_buffer_size)
6696}
6697
6698fn scene_estimate_fits_prepared_device(scene: &Scene, device: &wgpu::Device) -> bool {
6699    buffer_capacity_fits::<Vertex>(
6700        device,
6701        scene.statistics().estimated_tessellated_vertices().max(1),
6702    )
6703}
6704
6705fn scene_estimate_fits_streaming_device(
6706    scene: &Scene,
6707    device: &wgpu::Device,
6708    prefix: usize,
6709    current_capacity: usize,
6710) -> bool {
6711    let Some(required) = prefix.checked_add(scene.statistics().estimated_tessellated_vertices())
6712    else {
6713        return false;
6714    };
6715    required <= current_capacity
6716        || dynamic_vertex_capacity(required)
6717            .is_some_and(|capacity| buffer_capacity_fits::<Vertex>(device, capacity))
6718}
6719
6720fn particle_update_range(
6721    first_instance: usize,
6722    replacement_count: usize,
6723    current_count: usize,
6724) -> Result<Range<usize>, ParticleFieldError> {
6725    let end = first_instance
6726        .checked_add(replacement_count)
6727        .ok_or(ParticleFieldError::UpdateRangeOutOfBounds)?;
6728    (end <= current_count)
6729        .then_some(first_instance..end)
6730        .ok_or(ParticleFieldError::UpdateRangeOutOfBounds)
6731}
6732
6733fn validate_particle_staging_capacity(
6734    instances: &Vec<ParticleGpu>,
6735    target_len: usize,
6736) -> Result<(), RendererFrameError> {
6737    let requested_bytes = target_len
6738        .checked_mul(std::mem::size_of::<ParticleGpu>())
6739        .ok_or(RendererFrameError::GeometryCapacityTooLarge)?;
6740    (instances.capacity() >= target_len)
6741        .then_some(())
6742        .ok_or(RendererFrameError::ParticleAllocationFailed { requested_bytes })
6743}
6744
6745#[cfg(test)]
6746fn visible_particle_instances(
6747    instances: &[ParticleGpu],
6748    camera: CameraUniform,
6749    viewport: LogicalViewport,
6750) -> Result<Vec<ParticleGpu>, RendererFrameError> {
6751    visible_particle_count(instances, camera, viewport)?;
6752    Ok(instances
6753        .iter()
6754        .copied()
6755        .filter(|instance| instance.intersects_viewport(camera, viewport))
6756        .collect())
6757}
6758
6759fn visible_particle_count(
6760    instances: &[ParticleGpu],
6761    camera: CameraUniform,
6762    viewport: LogicalViewport,
6763) -> Result<usize, RendererFrameError> {
6764    let mut visible = 0;
6765    for instance in instances.iter().copied() {
6766        let Some(intersects) = instance.validated_viewport_intersection(camera, viewport) else {
6767            return Err(RendererFrameError::InvalidGeometryTransform);
6768        };
6769        visible += usize::from(intersects);
6770    }
6771    Ok(visible)
6772}
6773
6774fn particle_visible_index_is_selected(
6775    visible_index: usize,
6776    visible_count: usize,
6777    selected_count: usize,
6778) -> bool {
6779    if visible_count == 0 || selected_count == 0 {
6780        return false;
6781    }
6782    let before = visible_index as u128 * selected_count as u128 / visible_count as u128;
6783    let after = (visible_index as u128 + 1) * selected_count as u128 / visible_count as u128;
6784    before < after
6785}
6786
6787fn uniformly_sampled_index(sample_index: usize, source_count: usize, sample_count: usize) -> usize {
6788    debug_assert!(sample_index < sample_count);
6789    debug_assert!(sample_count <= source_count);
6790    (((sample_index as u128 + 1) * source_count as u128 - 1) / sample_count as u128) as usize
6791}
6792
6793fn particle_idle_statistics(instance_count: usize) -> ParticleStatistics {
6794    ParticleStatistics {
6795        submitted: instance_count,
6796        visibility_checked: 0,
6797        visible: 0,
6798        culled: 0,
6799        budget_limited: 0,
6800        dropped: 0,
6801        rendered: 0,
6802    }
6803}
6804
6805#[cfg(test)]
6806fn particle_statistics(
6807    instance_count: usize,
6808    visible: usize,
6809    rendered: usize,
6810) -> ParticleStatistics {
6811    particle_statistics_with_budget(instance_count, instance_count, visible, visible, rendered)
6812}
6813
6814fn particle_statistics_with_budget(
6815    instance_count: usize,
6816    visibility_checked: usize,
6817    visible: usize,
6818    selected: usize,
6819    rendered: usize,
6820) -> ParticleStatistics {
6821    ParticleStatistics {
6822        submitted: instance_count,
6823        visibility_checked,
6824        visible,
6825        culled: visibility_checked.saturating_sub(visible),
6826        budget_limited: instance_count
6827            .saturating_sub(visibility_checked)
6828            .saturating_add(visible.saturating_sub(selected)),
6829        dropped: 0,
6830        rendered,
6831    }
6832}
6833
6834fn prepare_scene_resources(
6835    device: &wgpu::Device,
6836    queue: &wgpu::Queue,
6837    renderer_identity: Arc<()>,
6838    scene: &Scene,
6839) -> Result<PreparedScene, PreparedSceneError> {
6840    if !scene_command_sources_are_portable(scene) {
6841        return Err(PreparedSceneError::InvalidGeometrySources);
6842    }
6843    if !scene_estimate_fits_prepared_device(scene, device) {
6844        return Err(PreparedSceneError::CapacityTooLarge);
6845    }
6846    let mut vertices = Vec::new();
6847    let mut draw_batches = Vec::new();
6848    let tessellation = tessellate_scene(scene, &mut vertices, &mut draw_batches)?;
6849    let geometry_extents = GeometryExtents::from_vertices(&vertices);
6850    if !geometry_sources_are_portable(GeometryValidationSource::Tessellated(&vertices)) {
6851        return Err(PreparedSceneError::InvalidGeometrySources);
6852    }
6853    if !buffer_capacity_fits::<Vertex>(device, vertices.len().max(1)) {
6854        return Err(PreparedSceneError::CapacityTooLarge);
6855    }
6856    // Retain the tessellator allocation directly. Wrapping a Vec is O(1) and
6857    // avoids an infallible caller-scale Vec -> Arc<[T]> copy after GPU writes.
6858    let vertices = Arc::new(vertices);
6859    let vertex_buffer = Arc::new(create_vertex_buffer(device, vertices.len()));
6860    if !vertices.is_empty() {
6861        queue.write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(&vertices));
6862        submit_pending_uploads(queue);
6863    }
6864    let vertex_count = vertices.len();
6865
6866    Ok(PreparedScene {
6867        renderer_identity,
6868        background: scene.background(),
6869        vertex_buffer,
6870        vertices,
6871        command_count: scene.command_count(),
6872        vertex_count,
6873        geometry_extents,
6874        draw_batches,
6875        tessellation,
6876        geometry_validation_cache: GeometryValidationCache::default(),
6877    })
6878}
6879
6880fn scene_command_sources_are_portable(scene: &Scene) -> bool {
6881    scene.commands().iter().all(|command| {
6882        is_portable_shader_source(command.depth())
6883            && command.screen_clip().is_none_or(|clip| {
6884                portable_vec2(clip.min().to_vec2()) && portable_vec2(clip.max().to_vec2())
6885            })
6886            && match command.command() {
6887                DrawCommand::Circle(circle) => {
6888                    portable_vec2(circle.center())
6889                        && is_portable_shader_source(circle.radius())
6890                        && portable_shape_style(circle.style())
6891                }
6892                DrawCommand::Rect(rectangle) => {
6893                    portable_vec2(rectangle.rect().min())
6894                        && portable_vec2(rectangle.rect().max())
6895                        && is_portable_shader_source(rectangle.corner_radius())
6896                        && portable_shape_style(rectangle.style())
6897                }
6898                DrawCommand::Line(line) => {
6899                    portable_vec2(line.from())
6900                        && portable_vec2(line.to())
6901                        && portable_stroke_style(line.stroke_style())
6902                }
6903                DrawCommand::Polyline(polyline) => {
6904                    polyline.points().iter().copied().all(portable_vec2)
6905                        && portable_stroke_style(polyline.stroke_style())
6906                }
6907            }
6908    })
6909}
6910
6911fn portable_vec2(value: Vec2) -> bool {
6912    is_portable_shader_source(value.x) && is_portable_shader_source(value.y)
6913}
6914
6915fn portable_shape_style(style: ShapeStyle) -> bool {
6916    style
6917        .stroke()
6918        .is_none_or(|stroke| is_portable_shader_source(stroke.width()))
6919        && style.shadow().is_none_or(|shadow| {
6920            portable_vec2(shadow.offset().to_vec2()) && is_portable_shader_source(shadow.spread())
6921        })
6922}
6923
6924fn portable_stroke_style(style: crate::StrokeStyle2d) -> bool {
6925    let stroke = style.stroke();
6926    is_portable_shader_source(stroke.width())
6927        && is_portable_shader_source(style.miter_limit())
6928        && style.dash_pattern().is_none_or(|dash| {
6929            dash.lengths()
6930                .iter()
6931                .copied()
6932                .chain([dash.phase()])
6933                .all(is_portable_shader_source)
6934        })
6935        && style.start_marker().is_none_or(|marker| {
6936            is_portable_shader_source(marker.length().get())
6937                && is_portable_shader_source(marker.width().get())
6938        })
6939        && style.end_marker().is_none_or(|marker| {
6940            is_portable_shader_source(marker.length().get())
6941                && is_portable_shader_source(marker.width().get())
6942        })
6943}
6944
6945fn restore_prepared_scene_resources(
6946    device: &wgpu::Device,
6947    queue: &wgpu::Queue,
6948    renderer_identity: Arc<()>,
6949    source: &PreparedScene,
6950) -> Result<PreparedScene, PreparedSceneError> {
6951    if !buffer_capacity_fits::<Vertex>(device, source.vertices.len().max(1)) {
6952        return Err(PreparedSceneError::CapacityTooLarge);
6953    }
6954    if !geometry_sources_are_portable(GeometryValidationSource::Tessellated(&source.vertices)) {
6955        return Err(PreparedSceneError::InvalidGeometrySources);
6956    }
6957    let requested_bytes = source
6958        .draw_batches
6959        .len()
6960        .checked_mul(std::mem::size_of::<PreparedDrawBatch>())
6961        .ok_or(PreparedSceneError::CapacityTooLarge)?;
6962    let mut draw_batches = Vec::new();
6963    draw_batches
6964        .try_reserve_exact(source.draw_batches.len())
6965        .map_err(|_| PreparedSceneError::AllocationFailed { requested_bytes })?;
6966    draw_batches.extend_from_slice(&source.draw_batches);
6967    let vertex_buffer = Arc::new(create_vertex_buffer(device, source.vertices.len()));
6968    if !source.vertices.is_empty() {
6969        queue.write_buffer(
6970            &vertex_buffer,
6971            0,
6972            bytemuck::cast_slice(source.vertices.as_ref()),
6973        );
6974        submit_pending_uploads(queue);
6975    }
6976
6977    Ok(PreparedScene {
6978        renderer_identity,
6979        background: source.background,
6980        vertex_buffer,
6981        vertices: Arc::clone(&source.vertices),
6982        command_count: source.command_count,
6983        vertex_count: source.vertex_count,
6984        geometry_extents: source.geometry_extents,
6985        draw_batches,
6986        tessellation: source.tessellation,
6987        geometry_validation_cache: GeometryValidationCache::default(),
6988    })
6989}
6990
6991fn restore_dynamic_mesh_resources(
6992    device: &wgpu::Device,
6993    queue: &wgpu::Queue,
6994    renderer_identity: Arc<()>,
6995    source: &DynamicMesh2d,
6996) -> Result<DynamicMesh2d, DynamicMeshError> {
6997    if !buffer_capacity_fits::<DynamicGpu>(device, source.vertex_capacity) {
6998        return Err(DynamicMeshError::CapacityTooLarge);
6999    }
7000    if let Some(budget) = source.budget {
7001        validate_dynamic_mesh_budget(budget, source.vertices.len())?;
7002    }
7003    let requested_bytes = dynamic_mesh_bytes(source.vertices.len())?;
7004    let mut vertices = Vec::new();
7005    vertices
7006        .try_reserve_exact(source.vertices.len())
7007        .map_err(|_| DynamicMeshError::AllocationFailed { requested_bytes })?;
7008    vertices.extend_from_slice(&source.vertices);
7009    if let Some(budget) = source.budget {
7010        validate_dynamic_retained_capacity(budget, &vertices)?;
7011    }
7012    let vertex_buffer = Arc::new(create_dynamic_vertex_buffer(device, source.vertex_capacity));
7013    if !vertices.is_empty() {
7014        queue.write_buffer(&vertex_buffer, 0, bytemuck::cast_slice(vertices.as_slice()));
7015        submit_pending_uploads(queue);
7016    }
7017    Ok(DynamicMesh2d {
7018        renderer_identity,
7019        vertex_buffer,
7020        vertices,
7021        vertex_capacity: source.vertex_capacity,
7022        geometry_extents: source.geometry_extents,
7023        geometry_validation_cache: GeometryValidationCache::default(),
7024        budget: source.budget,
7025    })
7026}
7027
7028fn restore_particle_field_resources(
7029    device: &wgpu::Device,
7030    _queue: &wgpu::Queue,
7031    renderer_identity: Arc<()>,
7032    source: &ParticleField2d,
7033) -> Result<ParticleField2d, ParticleFieldError> {
7034    validate_particle_retained_count(source.instances.len(), source.budget)?;
7035    if !buffer_capacity_fits::<ParticleGpu>(device, source.instance_capacity) {
7036        return Err(ParticleFieldError::CapacityTooLarge);
7037    }
7038    let requested_bytes = source
7039        .instances
7040        .len()
7041        .checked_mul(std::mem::size_of::<ParticleGpu>())
7042        .ok_or(ParticleFieldError::CapacityTooLarge)?;
7043    let mut instances = Vec::new();
7044    instances
7045        .try_reserve_exact(source.instances.len())
7046        .map_err(|_| ParticleFieldError::AllocationFailed { requested_bytes })?;
7047    instances.extend_from_slice(&source.instances);
7048    let visible_instances = allocate_particle_staging(instances.len(), source.budget)?;
7049    validate_particle_retained_capacities(
7050        instances.capacity(),
7051        visible_instances.capacity(),
7052        source.budget,
7053    )?;
7054    let instance_buffer = Arc::new(create_particle_instance_buffer(
7055        device,
7056        source.instance_capacity,
7057    ));
7058    Ok(ParticleField2d {
7059        renderer_identity,
7060        instance_buffer,
7061        instances,
7062        visible_instances,
7063        instance_capacity: source.instance_capacity,
7064        budget: source.budget,
7065        statistics: particle_idle_statistics(source.instances.len()),
7066    })
7067}
7068
7069#[allow(clippy::too_many_arguments)]
7070fn render_report(
7071    status: RenderStatus,
7072    tessellation: Duration,
7073    upload: Duration,
7074    camera_uniform_upload: Duration,
7075    surface_acquire: Duration,
7076    encode_submit_present: Duration,
7077    total_cpu: Duration,
7078    geometry_reused: bool,
7079    geometry_streamed: bool,
7080    tessellation_stats: TessellationStats,
7081) -> RenderReport {
7082    RenderReport {
7083        status,
7084        metrics: RendererFrameMetrics {
7085            tessellation,
7086            upload,
7087            camera_uniform_upload,
7088            surface_acquire,
7089            encode_submit_present,
7090            total_cpu,
7091            geometry_reused,
7092            geometry_streamed,
7093            tessellation_stats,
7094        },
7095    }
7096}
7097
7098struct PipelineResources {
7099    pipeline: wgpu::RenderPipeline,
7100    target_pipeline: wgpu::RenderPipeline,
7101    dynamic_pipeline: wgpu::RenderPipeline,
7102    particle_pipeline: wgpu::RenderPipeline,
7103    target_particle_pipeline: wgpu::RenderPipeline,
7104    heatmap_pipeline: wgpu::RenderPipeline,
7105    target_heatmap_pipeline: wgpu::RenderPipeline,
7106    composition_pipelines: CompositionPipelines,
7107    target_composition_pipelines: CompositionPipelines,
7108    camera_uniform_buffer: wgpu::Buffer,
7109    camera_bind_group: wgpu::BindGroup,
7110    camera_bind_group_layout: wgpu::BindGroupLayout,
7111    heatmap_uniform_buffer: wgpu::Buffer,
7112    heatmap_bind_group_layout: wgpu::BindGroupLayout,
7113}
7114
7115fn create_pipeline(
7116    device: &wgpu::Device,
7117    format: wgpu::TextureFormat,
7118    sample_count: u32,
7119) -> PipelineResources {
7120    let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
7121        label: Some("sim-engine flat color shader"),
7122        source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("primitive.wgsl"))),
7123    });
7124    let camera_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7125        label: Some("sim-engine camera uniform buffer"),
7126        size: std::mem::size_of::<CameraUniform>() as wgpu::BufferAddress,
7127        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7128        mapped_at_creation: false,
7129    });
7130    let camera_bind_group_layout =
7131        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
7132            label: Some("sim-engine camera bind group layout"),
7133            entries: &[wgpu::BindGroupLayoutEntry {
7134                binding: 0,
7135                visibility: wgpu::ShaderStages::VERTEX,
7136                ty: wgpu::BindingType::Buffer {
7137                    ty: wgpu::BufferBindingType::Uniform,
7138                    has_dynamic_offset: false,
7139                    min_binding_size: None,
7140                },
7141                count: None,
7142            }],
7143        });
7144    let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
7145        label: Some("sim-engine camera bind group"),
7146        layout: &camera_bind_group_layout,
7147        entries: &[wgpu::BindGroupEntry {
7148            binding: 0,
7149            resource: camera_uniform_buffer.as_entire_binding(),
7150        }],
7151    });
7152    let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
7153        label: Some("sim-engine shape pipeline layout"),
7154        bind_group_layouts: &[Some(&camera_bind_group_layout)],
7155        immediate_size: 0,
7156    });
7157    let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7158        label: Some("sim-engine shape pipeline"),
7159        layout: Some(&pipeline_layout),
7160        vertex: wgpu::VertexState {
7161            module: &shader,
7162            entry_point: Some("vs_main"),
7163            compilation_options: wgpu::PipelineCompilationOptions::default(),
7164            buffers: &[Some(Vertex::LAYOUT)],
7165        },
7166        primitive: wgpu::PrimitiveState {
7167            topology: wgpu::PrimitiveTopology::TriangleList,
7168            ..Default::default()
7169        },
7170        depth_stencil: None,
7171        multisample: wgpu::MultisampleState {
7172            count: sample_count,
7173            ..Default::default()
7174        },
7175        fragment: Some(wgpu::FragmentState {
7176            module: &shader,
7177            entry_point: Some("fs_main"),
7178            compilation_options: wgpu::PipelineCompilationOptions::default(),
7179            targets: &[Some(wgpu::ColorTargetState {
7180                format,
7181                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7182                write_mask: wgpu::ColorWrites::ALL,
7183            })],
7184        }),
7185        multiview_mask: None,
7186        cache: None,
7187    });
7188
7189    let target_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7190        label: Some("sim-engine target shape pipeline"),
7191        layout: Some(&pipeline_layout),
7192        vertex: wgpu::VertexState {
7193            module: &shader,
7194            entry_point: Some("vs_main"),
7195            compilation_options: wgpu::PipelineCompilationOptions::default(),
7196            buffers: &[Some(Vertex::LAYOUT)],
7197        },
7198        primitive: wgpu::PrimitiveState {
7199            topology: wgpu::PrimitiveTopology::TriangleList,
7200            ..Default::default()
7201        },
7202        depth_stencil: None,
7203        multisample: wgpu::MultisampleState::default(),
7204        fragment: Some(wgpu::FragmentState {
7205            module: &shader,
7206            entry_point: Some("fs_main"),
7207            compilation_options: wgpu::PipelineCompilationOptions::default(),
7208            targets: &[Some(wgpu::ColorTargetState {
7209                format,
7210                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7211                write_mask: wgpu::ColorWrites::ALL,
7212            })],
7213        }),
7214        multiview_mask: None,
7215        cache: None,
7216    });
7217
7218    let dynamic_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7219        label: Some("sim-engine dynamic mesh pipeline"),
7220        layout: Some(&pipeline_layout),
7221        vertex: wgpu::VertexState {
7222            module: &shader,
7223            entry_point: Some("dynamic_vs_main"),
7224            compilation_options: wgpu::PipelineCompilationOptions::default(),
7225            buffers: &[Some(DynamicGpu::LAYOUT)],
7226        },
7227        primitive: wgpu::PrimitiveState {
7228            topology: wgpu::PrimitiveTopology::TriangleList,
7229            ..Default::default()
7230        },
7231        depth_stencil: None,
7232        multisample: wgpu::MultisampleState {
7233            count: sample_count,
7234            ..Default::default()
7235        },
7236        fragment: Some(wgpu::FragmentState {
7237            module: &shader,
7238            entry_point: Some("fs_main"),
7239            compilation_options: wgpu::PipelineCompilationOptions::default(),
7240            targets: &[Some(wgpu::ColorTargetState {
7241                format,
7242                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7243                write_mask: wgpu::ColorWrites::ALL,
7244            })],
7245        }),
7246        multiview_mask: None,
7247        cache: None,
7248    });
7249
7250    let particle_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7251        label: Some("sim-engine particle pipeline"),
7252        layout: Some(&pipeline_layout),
7253        vertex: wgpu::VertexState {
7254            module: &shader,
7255            entry_point: Some("particle_vs_main"),
7256            compilation_options: wgpu::PipelineCompilationOptions::default(),
7257            buffers: &[Some(ParticleUnitVertex::LAYOUT), Some(ParticleGpu::LAYOUT)],
7258        },
7259        primitive: wgpu::PrimitiveState {
7260            topology: wgpu::PrimitiveTopology::TriangleList,
7261            ..Default::default()
7262        },
7263        depth_stencil: None,
7264        multisample: wgpu::MultisampleState {
7265            count: sample_count,
7266            ..Default::default()
7267        },
7268        fragment: Some(wgpu::FragmentState {
7269            module: &shader,
7270            entry_point: Some("fs_main"),
7271            compilation_options: wgpu::PipelineCompilationOptions::default(),
7272            targets: &[Some(wgpu::ColorTargetState {
7273                format,
7274                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7275                write_mask: wgpu::ColorWrites::ALL,
7276            })],
7277        }),
7278        multiview_mask: None,
7279        cache: None,
7280    });
7281
7282    let target_particle_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7283        label: Some("sim-engine target particle pipeline"),
7284        layout: Some(&pipeline_layout),
7285        vertex: wgpu::VertexState {
7286            module: &shader,
7287            entry_point: Some("particle_vs_main"),
7288            compilation_options: wgpu::PipelineCompilationOptions::default(),
7289            buffers: &[Some(ParticleUnitVertex::LAYOUT), Some(ParticleGpu::LAYOUT)],
7290        },
7291        primitive: wgpu::PrimitiveState {
7292            topology: wgpu::PrimitiveTopology::TriangleList,
7293            ..Default::default()
7294        },
7295        depth_stencil: None,
7296        multisample: wgpu::MultisampleState {
7297            count: 1,
7298            ..Default::default()
7299        },
7300        fragment: Some(wgpu::FragmentState {
7301            module: &shader,
7302            entry_point: Some("fs_main"),
7303            compilation_options: wgpu::PipelineCompilationOptions::default(),
7304            targets: &[Some(wgpu::ColorTargetState {
7305                format,
7306                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7307                write_mask: wgpu::ColorWrites::ALL,
7308            })],
7309        }),
7310        multiview_mask: None,
7311        cache: None,
7312    });
7313
7314    let heatmap_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7315        label: Some("sim-engine heatmap uniform buffer"),
7316        size: std::mem::size_of::<HeatmapUniform>() as wgpu::BufferAddress,
7317        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7318        mapped_at_creation: false,
7319    });
7320    let heatmap_bind_group_layout =
7321        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
7322            label: Some("sim-engine heatmap bind group layout"),
7323            entries: &[
7324                wgpu::BindGroupLayoutEntry {
7325                    binding: 0,
7326                    visibility: wgpu::ShaderStages::FRAGMENT,
7327                    ty: wgpu::BindingType::Texture {
7328                        multisampled: false,
7329                        view_dimension: wgpu::TextureViewDimension::D2,
7330                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
7331                    },
7332                    count: None,
7333                },
7334                wgpu::BindGroupLayoutEntry {
7335                    binding: 1,
7336                    visibility: wgpu::ShaderStages::FRAGMENT,
7337                    ty: wgpu::BindingType::Texture {
7338                        multisampled: false,
7339                        view_dimension: wgpu::TextureViewDimension::D2,
7340                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
7341                    },
7342                    count: None,
7343                },
7344                wgpu::BindGroupLayoutEntry {
7345                    binding: 2,
7346                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
7347                    ty: wgpu::BindingType::Buffer {
7348                        ty: wgpu::BufferBindingType::Uniform,
7349                        has_dynamic_offset: false,
7350                        min_binding_size: None,
7351                    },
7352                    count: None,
7353                },
7354            ],
7355        });
7356    let heatmap_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
7357        label: Some("sim-engine heatmap pipeline layout"),
7358        bind_group_layouts: &[Some(&heatmap_bind_group_layout)],
7359        immediate_size: 0,
7360    });
7361    let heatmap_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7362        label: Some("sim-engine heatmap pipeline"),
7363        layout: Some(&heatmap_pipeline_layout),
7364        vertex: wgpu::VertexState {
7365            module: &shader,
7366            entry_point: Some("heatmap_vs_main"),
7367            compilation_options: wgpu::PipelineCompilationOptions::default(),
7368            buffers: &[],
7369        },
7370        primitive: wgpu::PrimitiveState {
7371            topology: wgpu::PrimitiveTopology::TriangleList,
7372            ..Default::default()
7373        },
7374        depth_stencil: None,
7375        multisample: wgpu::MultisampleState {
7376            count: sample_count,
7377            ..Default::default()
7378        },
7379        fragment: Some(wgpu::FragmentState {
7380            module: &shader,
7381            entry_point: Some("heatmap_fs_main"),
7382            compilation_options: wgpu::PipelineCompilationOptions::default(),
7383            targets: &[Some(wgpu::ColorTargetState {
7384                format,
7385                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7386                write_mask: wgpu::ColorWrites::ALL,
7387            })],
7388        }),
7389        multiview_mask: None,
7390        cache: None,
7391    });
7392
7393    let target_heatmap_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
7394        label: Some("sim-engine render-target heatmap pipeline"),
7395        layout: Some(&heatmap_pipeline_layout),
7396        vertex: wgpu::VertexState {
7397            module: &shader,
7398            entry_point: Some("heatmap_vs_main"),
7399            compilation_options: wgpu::PipelineCompilationOptions::default(),
7400            buffers: &[],
7401        },
7402        primitive: wgpu::PrimitiveState {
7403            topology: wgpu::PrimitiveTopology::TriangleList,
7404            ..Default::default()
7405        },
7406        depth_stencil: None,
7407        multisample: wgpu::MultisampleState::default(),
7408        fragment: Some(wgpu::FragmentState {
7409            module: &shader,
7410            entry_point: Some("heatmap_fs_main"),
7411            compilation_options: wgpu::PipelineCompilationOptions::default(),
7412            targets: &[Some(wgpu::ColorTargetState {
7413                format,
7414                blend: Some(wgpu::BlendState::ALPHA_BLENDING),
7415                write_mask: wgpu::ColorWrites::ALL,
7416            })],
7417        }),
7418        multiview_mask: None,
7419        cache: None,
7420    });
7421
7422    let composition_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7423        label: Some("sim-engine composition uniform buffer"),
7424        size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
7425        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7426        mapped_at_creation: false,
7427    });
7428    let composition_secondary_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7429        label: Some("sim-engine composition secondary uniform buffer"),
7430        size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
7431        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7432        mapped_at_creation: false,
7433    });
7434    let composition_bind_group_layout =
7435        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
7436            label: Some("sim-engine composition bind group layout"),
7437            entries: &[
7438                wgpu::BindGroupLayoutEntry {
7439                    binding: 0,
7440                    visibility: wgpu::ShaderStages::FRAGMENT,
7441                    ty: wgpu::BindingType::Texture {
7442                        multisampled: false,
7443                        view_dimension: wgpu::TextureViewDimension::D2,
7444                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
7445                    },
7446                    count: None,
7447                },
7448                wgpu::BindGroupLayoutEntry {
7449                    binding: 1,
7450                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
7451                    ty: wgpu::BindingType::Buffer {
7452                        ty: wgpu::BufferBindingType::Uniform,
7453                        has_dynamic_offset: false,
7454                        min_binding_size: None,
7455                    },
7456                    count: None,
7457                },
7458            ],
7459        });
7460    let composition_pipeline_layout =
7461        device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
7462            label: Some("sim-engine composition pipeline layout"),
7463            bind_group_layouts: &[Some(&composition_bind_group_layout)],
7464            immediate_size: 0,
7465        });
7466    let composition_pipelines = CompositionPipelines {
7467        alpha: create_composition_pipeline(
7468            device,
7469            &shader,
7470            &composition_pipeline_layout,
7471            format,
7472            sample_count,
7473            BlendMode::Alpha,
7474        ),
7475        additive: create_composition_pipeline(
7476            device,
7477            &shader,
7478            &composition_pipeline_layout,
7479            format,
7480            sample_count,
7481            BlendMode::Additive,
7482        ),
7483        replace: create_composition_pipeline(
7484            device,
7485            &shader,
7486            &composition_pipeline_layout,
7487            format,
7488            sample_count,
7489            BlendMode::Replace,
7490        ),
7491        uniform_buffer: composition_uniform_buffer,
7492        secondary_uniform_buffer: composition_secondary_uniform_buffer,
7493        bind_group_layout: composition_bind_group_layout,
7494    };
7495    let target_composition_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
7496        label: Some("sim-engine target composition uniform buffer"),
7497        size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
7498        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7499        mapped_at_creation: false,
7500    });
7501    let target_composition_secondary_uniform_buffer =
7502        device.create_buffer(&wgpu::BufferDescriptor {
7503            label: Some("sim-engine target composition secondary uniform buffer"),
7504            size: std::mem::size_of::<CompositeUniform>() as wgpu::BufferAddress,
7505            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
7506            mapped_at_creation: false,
7507        });
7508    let target_composition_bind_group_layout =
7509        device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
7510            label: Some("sim-engine target composition bind group layout"),
7511            entries: &[
7512                wgpu::BindGroupLayoutEntry {
7513                    binding: 0,
7514                    visibility: wgpu::ShaderStages::FRAGMENT,
7515                    ty: wgpu::BindingType::Texture {
7516                        multisampled: false,
7517                        view_dimension: wgpu::TextureViewDimension::D2,
7518                        sample_type: wgpu::TextureSampleType::Float { filterable: false },
7519                    },
7520                    count: None,
7521                },
7522                wgpu::BindGroupLayoutEntry {
7523                    binding: 1,
7524                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
7525                    ty: wgpu::BindingType::Buffer {
7526                        ty: wgpu::BufferBindingType::Uniform,
7527                        has_dynamic_offset: false,
7528                        min_binding_size: None,
7529                    },
7530                    count: None,
7531                },
7532            ],
7533        });
7534    let target_composition_pipeline_layout =
7535        device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
7536            label: Some("sim-engine target composition pipeline layout"),
7537            bind_group_layouts: &[Some(&target_composition_bind_group_layout)],
7538            immediate_size: 0,
7539        });
7540    let target_composition_pipelines = CompositionPipelines {
7541        alpha: create_composition_pipeline(
7542            device,
7543            &shader,
7544            &target_composition_pipeline_layout,
7545            format,
7546            1,
7547            BlendMode::Alpha,
7548        ),
7549        additive: create_composition_pipeline(
7550            device,
7551            &shader,
7552            &target_composition_pipeline_layout,
7553            format,
7554            1,
7555            BlendMode::Additive,
7556        ),
7557        replace: create_composition_pipeline(
7558            device,
7559            &shader,
7560            &target_composition_pipeline_layout,
7561            format,
7562            1,
7563            BlendMode::Replace,
7564        ),
7565        uniform_buffer: target_composition_uniform_buffer,
7566        secondary_uniform_buffer: target_composition_secondary_uniform_buffer,
7567        bind_group_layout: target_composition_bind_group_layout,
7568    };
7569
7570    PipelineResources {
7571        pipeline,
7572        target_pipeline,
7573        dynamic_pipeline,
7574        particle_pipeline,
7575        target_particle_pipeline,
7576        heatmap_pipeline,
7577        target_heatmap_pipeline,
7578        composition_pipelines,
7579        target_composition_pipelines,
7580        camera_uniform_buffer,
7581        camera_bind_group,
7582        camera_bind_group_layout,
7583        heatmap_uniform_buffer,
7584        heatmap_bind_group_layout,
7585    }
7586}
7587
7588fn preferred_sample_count(adapter: &wgpu::Adapter, format: wgpu::TextureFormat) -> u32 {
7589    let flags = adapter.get_texture_format_features(format).flags;
7590    if flags.contains(
7591        wgpu::TextureFormatFeatureFlags::MULTISAMPLE_X4
7592            | wgpu::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE,
7593    ) {
7594        PREFERRED_SAMPLE_COUNT
7595    } else {
7596        1
7597    }
7598}
7599
7600fn create_vertex_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
7601    device.create_buffer(&wgpu::BufferDescriptor {
7602        label: Some("sim-engine vertex buffer"),
7603        size: (capacity.max(1) * std::mem::size_of::<Vertex>()) as wgpu::BufferAddress,
7604        usage: wgpu::BufferUsages::VERTEX
7605            | wgpu::BufferUsages::COPY_DST
7606            | wgpu::BufferUsages::COPY_SRC,
7607        mapped_at_creation: false,
7608    })
7609}
7610
7611fn create_dynamic_vertex_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
7612    device.create_buffer(&wgpu::BufferDescriptor {
7613        label: Some("sim-engine dynamic vertex buffer"),
7614        size: (capacity.max(1) * std::mem::size_of::<DynamicGpu>()) as wgpu::BufferAddress,
7615        usage: wgpu::BufferUsages::VERTEX
7616            | wgpu::BufferUsages::COPY_DST
7617            | wgpu::BufferUsages::COPY_SRC,
7618        mapped_at_creation: false,
7619    })
7620}
7621
7622fn scalar_field_extent(field: &ScalarField) -> Result<wgpu::Extent3d, ScalarFieldTextureError> {
7623    let width =
7624        u32::try_from(field.width()).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7625    let height =
7626        u32::try_from(field.height()).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7627    let _bytes_per_row = width
7628        .checked_mul(std::mem::size_of::<f32>() as u32)
7629        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7630    Ok(wgpu::Extent3d {
7631        width,
7632        height,
7633        depth_or_array_layers: 1,
7634    })
7635}
7636
7637fn clone_scalar_field_for_restore(
7638    source: &ScalarField,
7639) -> Result<ScalarField, ScalarFieldTextureError> {
7640    let requested_bytes = source
7641        .values()
7642        .len()
7643        .checked_mul(std::mem::size_of::<f32>())
7644        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7645    let mut values = Vec::new();
7646    values
7647        .try_reserve_exact(source.values().len())
7648        .map_err(|_| ScalarFieldTextureError::AllocationFailed { requested_bytes })?;
7649    values.extend_from_slice(source.values());
7650    // The retained source already satisfies ScalarField's shape and finite
7651    // invariants. Keep the impossible defensive branch structured.
7652    ScalarField::new(source.width(), source.height(), values)
7653        .map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)
7654}
7655
7656fn scalar_value_range_extent(minimum: f32, maximum: f32) -> Option<f32> {
7657    if !is_portable_shader_source(minimum)
7658        || !is_portable_shader_source(maximum)
7659        || maximum <= minimum
7660    {
7661        return None;
7662    }
7663    let extent = maximum - minimum;
7664    (is_portable_shader_source(extent) && extent > 0.0).then_some(extent)
7665}
7666
7667fn scalar_field_sources_are_portable(field: &ScalarField) -> bool {
7668    if field
7669        .values()
7670        .iter()
7671        .copied()
7672        .any(|value| !is_portable_shader_source(value))
7673    {
7674        return false;
7675    }
7676    let (minimum, maximum) = field.value_range();
7677    let extent = f64::from(maximum) - f64::from(minimum);
7678    extent.is_finite() && extent <= f64::from(MAX_PORTABLE_SHADER_VALUE)
7679}
7680
7681fn scalar_normalization_is_portable(
7682    texture: &ScalarFieldTexture,
7683    minimum: f32,
7684    value_extent: f32,
7685) -> bool {
7686    if !is_portable_shader_source(minimum)
7687        || !is_portable_shader_source(value_extent)
7688        || value_extent <= 0.0
7689    {
7690        return false;
7691    }
7692    let Some(numerator) = shader_interval_sum_range([
7693        (
7694            f64::from(texture.source_minimum),
7695            f64::from(texture.source_maximum),
7696        ),
7697        (-f64::from(minimum), -f64::from(minimum)),
7698    ]) else {
7699        return false;
7700    };
7701    [numerator.0, numerator.1].into_iter().all(|value| {
7702        let normalized = value / f64::from(value_extent);
7703        normalized.is_finite() && normalized.abs() <= f64::from(MAX_PORTABLE_SHADER_VALUE)
7704    })
7705}
7706
7707fn compact_scalar_field_for_retention(
7708    field: ScalarField,
7709) -> Result<ScalarField, ScalarFieldTextureError> {
7710    let requested_bytes = field
7711        .values()
7712        .len()
7713        .checked_mul(std::mem::size_of::<f32>())
7714        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7715    if field.value_allocation_bytes() <= requested_bytes {
7716        return Ok(field);
7717    }
7718    clone_scalar_field_for_restore(&field)
7719}
7720
7721fn premultiplied_wgpu_color(color: Color) -> wgpu::Color {
7722    let [red, green, blue, alpha] = color.to_array();
7723    wgpu::Color {
7724        r: f64::from(red * alpha),
7725        g: f64::from(green * alpha),
7726        b: f64::from(blue * alpha),
7727        a: f64::from(alpha),
7728    }
7729}
7730
7731fn create_scalar_field_texture(
7732    device: &wgpu::Device,
7733    field: &ScalarField,
7734) -> Result<wgpu::Texture, ScalarFieldTextureError> {
7735    let extent = scalar_field_extent(field)?;
7736    let limits = device.limits();
7737    if extent.width > limits.max_texture_dimension_2d
7738        || extent.height > limits.max_texture_dimension_2d
7739    {
7740        return Err(ScalarFieldTextureError::DimensionsTooLarge);
7741    }
7742    Ok(device.create_texture(&wgpu::TextureDescriptor {
7743        label: Some("sim-engine scalar field texture"),
7744        size: extent,
7745        mip_level_count: 1,
7746        sample_count: 1,
7747        dimension: wgpu::TextureDimension::D2,
7748        format: wgpu::TextureFormat::R32Float,
7749        usage: wgpu::TextureUsages::TEXTURE_BINDING
7750            | wgpu::TextureUsages::COPY_DST
7751            | wgpu::TextureUsages::COPY_SRC,
7752        view_formats: &[],
7753    }))
7754}
7755
7756fn validate_scalar_field_device_extent(
7757    device: &wgpu::Device,
7758    field: &ScalarField,
7759) -> Result<wgpu::Extent3d, ScalarFieldTextureError> {
7760    let extent = scalar_field_extent(field)?;
7761    let limit = device.limits().max_texture_dimension_2d;
7762    if extent.width > limit || extent.height > limit {
7763        return Err(ScalarFieldTextureError::DimensionsTooLarge);
7764    }
7765    Ok(extent)
7766}
7767
7768fn upload_scalar_field_texture(
7769    queue: &wgpu::Queue,
7770    texture: &wgpu::Texture,
7771    field: &ScalarField,
7772) -> Result<(), ScalarFieldTextureError> {
7773    let extent = scalar_field_extent(field)?;
7774    queue.write_texture(
7775        wgpu::TexelCopyTextureInfo {
7776            texture,
7777            mip_level: 0,
7778            origin: wgpu::Origin3d::ZERO,
7779            aspect: wgpu::TextureAspect::All,
7780        },
7781        bytemuck::cast_slice(field.values()),
7782        wgpu::TexelCopyBufferLayout {
7783            offset: 0,
7784            bytes_per_row: Some(extent.width * std::mem::size_of::<f32>() as u32),
7785            rows_per_image: Some(extent.height),
7786        },
7787        extent,
7788    );
7789    submit_pending_uploads(queue);
7790    Ok(())
7791}
7792
7793fn upload_scalar_field_texture_region(
7794    queue: &wgpu::Queue,
7795    texture: &wgpu::Texture,
7796    x: usize,
7797    y: usize,
7798    width: usize,
7799    height: usize,
7800    values: &[f32],
7801) -> Result<(), ScalarFieldTextureError> {
7802    let width = u32::try_from(width).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7803    let height = u32::try_from(height).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7804    let x = u32::try_from(x).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7805    let y = u32::try_from(y).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7806    let bytes_per_row = width
7807        .checked_mul(std::mem::size_of::<f32>() as u32)
7808        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7809    queue.write_texture(
7810        wgpu::TexelCopyTextureInfo {
7811            texture,
7812            mip_level: 0,
7813            origin: wgpu::Origin3d { x, y, z: 0 },
7814            aspect: wgpu::TextureAspect::All,
7815        },
7816        bytemuck::cast_slice(values),
7817        wgpu::TexelCopyBufferLayout {
7818            offset: 0,
7819            bytes_per_row: Some(bytes_per_row),
7820            rows_per_image: Some(height),
7821        },
7822        wgpu::Extent3d {
7823            width,
7824            height,
7825            depth_or_array_layers: 1,
7826        },
7827    );
7828    submit_pending_uploads(queue);
7829    Ok(())
7830}
7831
7832/// Submits deferred `Queue::write_*` transfers without waiting for GPU completion.
7833///
7834/// Native `wgpu` retains staging allocations until a queue submission starts
7835/// their transfer. Standalone retained-resource mutations call this immediately;
7836/// render paths instead combine their writes with the draw submission.
7837pub(super) fn submit_pending_uploads(queue: &wgpu::Queue) {
7838    let _ = queue.submit([]);
7839}
7840
7841#[allow(clippy::too_many_arguments)]
7842fn validate_scalar_field_texture_region(
7843    texture_width: usize,
7844    texture_height: usize,
7845    x: usize,
7846    y: usize,
7847    width: usize,
7848    height: usize,
7849    value_count: usize,
7850) -> Result<(), ScalarFieldTextureError> {
7851    let expected = width
7852        .checked_mul(height)
7853        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7854    if value_count != expected {
7855        return Err(ScalarFieldTextureError::InvalidUpdateValueCount);
7856    }
7857    if width == 0
7858        || height == 0
7859        || x.checked_add(width).is_none_or(|end| end > texture_width)
7860        || y.checked_add(height).is_none_or(|end| end > texture_height)
7861    {
7862        return Err(ScalarFieldTextureError::UpdateRegionOutOfBounds);
7863    }
7864    for value in [x, y, width, height] {
7865        u32::try_from(value).map_err(|_| ScalarFieldTextureError::DimensionsTooLarge)?;
7866    }
7867    u32::try_from(width)
7868        .ok()
7869        .and_then(|width| width.checked_mul(std::mem::size_of::<f32>() as u32))
7870        .ok_or(ScalarFieldTextureError::DimensionsTooLarge)?;
7871    Ok(())
7872}
7873
7874fn scalar_region_result_range(
7875    field: &ScalarField,
7876    x: usize,
7877    y: usize,
7878    width: usize,
7879    height: usize,
7880    values: &[f32],
7881) -> (f32, f32) {
7882    let mut minimum = f32::INFINITY;
7883    let mut maximum = f32::NEG_INFINITY;
7884    for row in 0..field.height() {
7885        for column in 0..field.width() {
7886            let value = if (x..x + width).contains(&column) && (y..y + height).contains(&row) {
7887                values[(row - y) * width + (column - x)]
7888            } else {
7889                field.values()[row * field.width() + column]
7890            };
7891            minimum = minimum.min(value);
7892            maximum = maximum.max(value);
7893        }
7894    }
7895    (minimum, maximum)
7896}
7897
7898fn create_scalar_field_texture_resources(
7899    device: &wgpu::Device,
7900    queue: &wgpu::Queue,
7901    renderer_identity: Arc<()>,
7902    field: ScalarField,
7903) -> Result<ScalarFieldTexture, ScalarFieldTextureError> {
7904    validate_scalar_field_device_extent(device, &field)?;
7905    if !scalar_field_sources_are_portable(&field) {
7906        return Err(ScalarFieldTextureError::NonPortableValue);
7907    }
7908    let field = compact_scalar_field_for_retention(field)?;
7909    let (source_minimum, source_maximum) = field.value_range();
7910    let texture = create_scalar_field_texture(device, &field)?;
7911    upload_scalar_field_texture(queue, &texture, &field)?;
7912    Ok(ScalarFieldTexture {
7913        renderer_identity,
7914        texture,
7915        field,
7916        source_minimum,
7917        source_maximum,
7918    })
7919}
7920
7921fn color_map_lut(color_map: &ColorMap) -> [u8; COLOR_MAP_LUT_SIZE as usize * 4] {
7922    let mut bytes = [0_u8; COLOR_MAP_LUT_SIZE as usize * 4];
7923    for index in 0..COLOR_MAP_LUT_SIZE {
7924        let color = color_map.sample_normalized(index as f32 / (COLOR_MAP_LUT_SIZE - 1) as f32);
7925        let offset = index as usize * 4;
7926        bytes[offset..offset + 4].copy_from_slice(
7927            &color
7928                .to_array()
7929                .map(|channel| (channel * 255.0).round() as u8),
7930        );
7931    }
7932    bytes
7933}
7934
7935fn create_cached_color_map(
7936    device: &wgpu::Device,
7937    queue: &wgpu::Queue,
7938    lut: [u8; COLOR_MAP_LUT_SIZE as usize * 4],
7939) -> CachedColorMap {
7940    let texture = device.create_texture(&wgpu::TextureDescriptor {
7941        label: Some("sim-engine color map texture"),
7942        size: wgpu::Extent3d {
7943            width: COLOR_MAP_LUT_SIZE,
7944            height: 1,
7945            depth_or_array_layers: 1,
7946        },
7947        mip_level_count: 1,
7948        sample_count: 1,
7949        dimension: wgpu::TextureDimension::D2,
7950        format: wgpu::TextureFormat::Rgba8Unorm,
7951        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
7952        view_formats: &[],
7953    });
7954    queue.write_texture(
7955        wgpu::TexelCopyTextureInfo {
7956            texture: &texture,
7957            mip_level: 0,
7958            origin: wgpu::Origin3d::ZERO,
7959            aspect: wgpu::TextureAspect::All,
7960        },
7961        &lut,
7962        wgpu::TexelCopyBufferLayout {
7963            offset: 0,
7964            bytes_per_row: Some(1024),
7965            rows_per_image: Some(1),
7966        },
7967        wgpu::Extent3d {
7968            width: COLOR_MAP_LUT_SIZE,
7969            height: 1,
7970            depth_or_array_layers: 1,
7971        },
7972    );
7973    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
7974    CachedColorMap {
7975        lut,
7976        _texture: texture,
7977        view,
7978    }
7979}
7980
7981fn create_submitted_particle_unit_buffer(
7982    device: &wgpu::Device,
7983    queue: &wgpu::Queue,
7984) -> wgpu::Buffer {
7985    let buffer = device.create_buffer(&wgpu::BufferDescriptor {
7986        label: Some("sim-engine particle unit quad buffer"),
7987        size: (6 * std::mem::size_of::<ParticleUnitVertex>()) as wgpu::BufferAddress,
7988        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
7989        mapped_at_creation: false,
7990    });
7991    let unit_quad = [
7992        ParticleUnitVertex {
7993            direction: [-1.0, -1.0],
7994        },
7995        ParticleUnitVertex {
7996            direction: [1.0, -1.0],
7997        },
7998        ParticleUnitVertex {
7999            direction: [1.0, 1.0],
8000        },
8001        ParticleUnitVertex {
8002            direction: [-1.0, -1.0],
8003        },
8004        ParticleUnitVertex {
8005            direction: [1.0, 1.0],
8006        },
8007        ParticleUnitVertex {
8008            direction: [-1.0, 1.0],
8009        },
8010    ];
8011    queue.write_buffer(&buffer, 0, bytemuck::cast_slice(&unit_quad));
8012    submit_pending_uploads(queue);
8013    buffer
8014}
8015
8016fn create_particle_instance_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
8017    device.create_buffer(&wgpu::BufferDescriptor {
8018        label: Some("sim-engine particle instance buffer"),
8019        size: (capacity.max(1) * std::mem::size_of::<ParticleGpu>()) as wgpu::BufferAddress,
8020        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
8021        mapped_at_creation: false,
8022    })
8023}
8024
8025mod config;
8026mod frame;
8027mod glyph;
8028mod image;
8029mod mesh3d;
8030mod tessellation;
8031mod visualization;
8032use config::{
8033    MultisampleTarget, create_multisample_target, logical_to_physical_screen,
8034    physical_to_logical_screen, validate_scale_factor, validate_surface_dimensions,
8035};
8036pub use config::{RendererPresentMode, RendererSurfacePresentMode, WgpuRendererOptions};
8037pub use frame::{
8038    FrameBudget, FrameBudgetResource, FrameComposer, FrameComposerError, FramePassOptions,
8039    FrameReport, FrameSourceKind, FrameSourceStatistics, FrameStatistics,
8040};
8041pub use glyph::{
8042    GlyphAtlas2d, GlyphAtlasBudget, GlyphAtlasEntry, GlyphError, GlyphId, GlyphRun2d,
8043    GlyphRunBounds, GlyphRunBudget, GlyphRunStatistics, GlyphUploadReport, PositionedGlyph2d,
8044};
8045pub use image::{
8046    Image2d, ImageBatch2d, ImageBatchBudget, ImageBatchUploadReport, ImageBudget, ImageError,
8047    ImageSampling, ImageSprite2d, ImageTexelRect, ImageUploadReport,
8048};
8049use image::{ImageRenderer, ImageUniform};
8050use mesh3d::Mesh3dRenderer;
8051pub use mesh3d::{
8052    Mesh3dInstance, Mesh3dRenderError, Mesh3dRenderReport, Mesh3dResourceError, Object3dId,
8053    RenderTarget3d, RetainedMesh3d, Scene3d, Scene3dError, Scene3dRestoreReport,
8054};
8055use tessellation::{
8056    logical_viewport_scissor, offset_scissor, screen_clip_to_scissor, tessellate_scene,
8057};
8058use visualization::{CachedColorMap, CompositionPipelines, create_composition_pipeline};
8059pub use visualization::{
8060    LayeredVisualizationError, LayeredVisualizationOptions, LayeredVisualizationReport,
8061};
8062
8063#[cfg(test)]
8064use tessellation::world_vertex;
8065
8066#[cfg(test)]
8067mod tests;