Skip to main content

sim_engine/renderer/frame/
mod.rs

1use std::error::Error;
2use std::fmt;
3use std::sync::Arc;
4use std::time::Duration;
5
6#[cfg(test)]
7use super::ImageSprite2d;
8use super::{
9    BlendMode, COLOR_MAP_LUT_SIZE, Camera2d, CameraUniform, Color, ColorMap, CompositeUniform,
10    DynamicMesh2d, GeometryExtents, GeometryValidationCache, GeometryValidationSource, GpuTimingId,
11    HeatmapUniform, Image2d, ImageBatch2d, ImageBatchPlacement, ImageSampling, ImageTexelRect,
12    ImageUniform, LogicalScreenPosition, LogicalViewport, LogicalViewportRegion, ParticleField2d,
13    ParticleGpu, ParticleStatistics, PreparedDrawBatch, PreparedScene, PreparedScreenScene, Rect,
14    RenderStatus, RenderTarget2d, RendererFrameError, RendererFrameMetrics, ScalarFieldSampling,
15    ScalarFieldTexture, Scene, ScissorRect, ScreenClipRect, ScreenScene, TessellationStats, Vec2,
16    Vertex, WgpuRenderer, geometry_is_safe_for, geometry_is_safe_for_cached, image,
17    is_portable_shader_source, logical_viewport_scissor, offset_scissor,
18    particle_statistics_with_budget, particle_visible_index_is_selected, render_report,
19    scalar_normalization_is_portable, scene_estimate_fits_streaming_device, screen_camera,
20    screen_clip_to_scissor, tessellate_scene, uniformly_sampled_index,
21    validate_particle_staging_capacity,
22};
23
24mod cache;
25mod compose;
26mod encoding;
27#[cfg(test)]
28pub(super) use encoding::assert_gpu_encoding_contract;
29mod present;
30mod streaming;
31#[cfg(test)]
32mod tests;
33mod uniform_uploads;
34pub(super) use cache::FrameCache;
35#[cfg(test)]
36pub(super) use cache::assert_gpu_binding_sharing_contract;
37pub use cache::{FrameCacheBudget, FrameCacheStatistics};
38#[cfg(test)]
39pub(super) use uniform_uploads::assert_gpu_uniform_upload_contract;
40
41/// Work category constrained by a [`FrameBudget`].
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum FrameBudgetResource {
44    /// Number of ordered sources in one frame.
45    Passes,
46    /// Scene commands referenced by the frame.
47    Commands,
48    /// Generated or retained vertices referenced by the frame.
49    Vertices,
50    /// Bytes uploaded while preparing the frame.
51    UploadBytes,
52    /// Nominal retained texel-storage bytes referenced by images, fields, or targets.
53    TextureBytes,
54    /// Conservative number of GPU draw calls encoded by the frame.
55    DrawCalls,
56}
57
58/// Explicit upper bounds for one heterogeneous presentation frame.
59///
60/// The default is deliberately finite. Production hosts should select limits
61/// from their frame-time and memory budgets instead of treating it as a device
62/// capability query.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct FrameBudget {
65    max_passes: usize,
66    max_commands: usize,
67    max_vertices: usize,
68    max_upload_bytes: usize,
69    max_texture_bytes: usize,
70    max_draw_calls: usize,
71}
72
73impl FrameBudget {
74    /// Creates an exact set of frame-work limits.
75    pub const fn new(
76        max_passes: usize,
77        max_commands: usize,
78        max_vertices: usize,
79        max_upload_bytes: usize,
80        max_texture_bytes: usize,
81        max_draw_calls: usize,
82    ) -> Self {
83        Self {
84            max_passes,
85            max_commands,
86            max_vertices,
87            max_upload_bytes,
88            max_texture_bytes,
89            max_draw_calls,
90        }
91    }
92
93    /// Returns the maximum number of ordered sources.
94    pub const fn max_passes(self) -> usize {
95        self.max_passes
96    }
97
98    /// Returns the maximum referenced scene-command count.
99    pub const fn max_commands(self) -> usize {
100        self.max_commands
101    }
102
103    /// Returns the maximum referenced or generated vertex count.
104    pub const fn max_vertices(self) -> usize {
105        self.max_vertices
106    }
107
108    /// Returns the maximum bytes uploaded while presenting the frame.
109    pub const fn max_upload_bytes(self) -> usize {
110        self.max_upload_bytes
111    }
112
113    /// Returns the maximum referenced nominal texel-storage bytes.
114    pub const fn max_texture_bytes(self) -> usize {
115        self.max_texture_bytes
116    }
117
118    /// Returns the maximum conservative draw-call count.
119    pub const fn max_draw_calls(self) -> usize {
120        self.max_draw_calls
121    }
122}
123
124impl Default for FrameBudget {
125    fn default() -> Self {
126        Self::new(
127            64,
128            100_000,
129            4_000_000,
130            256 * 1024 * 1024,
131            512 * 1024 * 1024,
132            65_536,
133        )
134    }
135}
136
137/// Shared placement and ordering state for one frame item.
138#[derive(Debug, Clone, Copy, PartialEq, Default)]
139pub struct FramePassOptions {
140    order: i32,
141    viewport: Option<LogicalViewportRegion>,
142    clip: Option<ScreenClipRect>,
143}
144
145impl FramePassOptions {
146    /// Creates a full-surface, unclipped item at `order`.
147    pub const fn new(order: i32) -> Self {
148        Self {
149            order,
150            viewport: None,
151            clip: None,
152        }
153    }
154
155    /// Positions the item in a logical sub-viewport of the surface.
156    pub const fn with_viewport(mut self, viewport: LogicalViewportRegion) -> Self {
157        self.viewport = Some(viewport);
158        self
159    }
160
161    /// Intersects all source-local clips with an additional item-local clip.
162    pub const fn with_clip(mut self, clip: ScreenClipRect) -> Self {
163        self.clip = Some(clip);
164        self
165    }
166
167    /// Returns the stable ordering key. Lower values draw first.
168    pub const fn order(self) -> i32 {
169        self.order
170    }
171
172    /// Returns the optional positioned logical viewport.
173    pub const fn viewport(self) -> Option<LogicalViewportRegion> {
174        self.viewport
175    }
176
177    /// Returns the optional item-local logical clip.
178    pub const fn clip(self) -> Option<ScreenClipRect> {
179        self.clip
180    }
181}
182
183/// Renderer-owned source category used in structured composer errors.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum FrameSourceKind {
186    /// Streaming world-space or fixed-screen scene tessellated for this frame.
187    StreamingScene,
188    /// Immutable prepared world or screen geometry.
189    PreparedScene,
190    /// Mutable retained triangle geometry.
191    DynamicMesh,
192    /// Instanced retained particle resource.
193    ParticleField,
194    /// Renderer-owned scalar texture.
195    ScalarField,
196    /// Retained sRGB RGBA image or atlas.
197    Image,
198    /// Retained host-shaped glyph atlas and positioned run.
199    Glyph,
200    /// Offscreen color texture.
201    RenderTarget,
202}
203
204/// Ordered frame inputs grouped by their renderer source path.
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
206pub struct FrameSourceStatistics {
207    streaming_scenes: usize,
208    prepared_scenes: usize,
209    dynamic_meshes: usize,
210    particle_fields: usize,
211    scalar_fields: usize,
212    images: usize,
213    glyph_runs: usize,
214    render_targets: usize,
215}
216
217impl FrameSourceStatistics {
218    /// Returns streaming world and fixed-screen scenes.
219    pub const fn streaming_scenes(self) -> usize {
220        self.streaming_scenes
221    }
222
223    /// Returns immutable prepared world and fixed-screen scenes.
224    pub const fn prepared_scenes(self) -> usize {
225        self.prepared_scenes
226    }
227
228    /// Returns retained dynamic triangle meshes.
229    pub const fn dynamic_meshes(self) -> usize {
230        self.dynamic_meshes
231    }
232
233    /// Returns retained particle fields.
234    pub const fn particle_fields(self) -> usize {
235        self.particle_fields
236    }
237
238    /// Returns retained scalar fields.
239    pub const fn scalar_fields(self) -> usize {
240        self.scalar_fields
241    }
242
243    /// Returns image, world-image, and atlas-batch sources.
244    pub const fn images(self) -> usize {
245        self.images
246    }
247
248    /// Returns host-shaped glyph runs.
249    pub const fn glyph_runs(self) -> usize {
250        self.glyph_runs
251    }
252
253    /// Returns composed 2D or retained-3D color targets.
254    pub const fn render_targets(self) -> usize {
255        self.render_targets
256    }
257
258    /// Returns all accepted frame sources.
259    pub const fn total(self) -> usize {
260        self.streaming_scenes
261            .saturating_add(self.prepared_scenes)
262            .saturating_add(self.dynamic_meshes)
263            .saturating_add(self.particle_fields)
264            .saturating_add(self.scalar_fields)
265            .saturating_add(self.images)
266            .saturating_add(self.glyph_runs)
267            .saturating_add(self.render_targets)
268    }
269
270    const fn single(source: FrameSourceKind) -> Self {
271        let mut counts = Self {
272            streaming_scenes: 0,
273            prepared_scenes: 0,
274            dynamic_meshes: 0,
275            particle_fields: 0,
276            scalar_fields: 0,
277            images: 0,
278            glyph_runs: 0,
279            render_targets: 0,
280        };
281        match source {
282            FrameSourceKind::StreamingScene => counts.streaming_scenes = 1,
283            FrameSourceKind::PreparedScene => counts.prepared_scenes = 1,
284            FrameSourceKind::DynamicMesh => counts.dynamic_meshes = 1,
285            FrameSourceKind::ParticleField => counts.particle_fields = 1,
286            FrameSourceKind::ScalarField => counts.scalar_fields = 1,
287            FrameSourceKind::Image => counts.images = 1,
288            FrameSourceKind::Glyph => counts.glyph_runs = 1,
289            FrameSourceKind::RenderTarget => counts.render_targets = 1,
290        }
291        counts
292    }
293
294    const fn adding(self, other: Self) -> Self {
295        Self {
296            streaming_scenes: self.streaming_scenes.saturating_add(other.streaming_scenes),
297            prepared_scenes: self.prepared_scenes.saturating_add(other.prepared_scenes),
298            dynamic_meshes: self.dynamic_meshes.saturating_add(other.dynamic_meshes),
299            particle_fields: self.particle_fields.saturating_add(other.particle_fields),
300            scalar_fields: self.scalar_fields.saturating_add(other.scalar_fields),
301            images: self.images.saturating_add(other.images),
302            glyph_runs: self.glyph_runs.saturating_add(other.glyph_runs),
303            render_targets: self.render_targets.saturating_add(other.render_targets),
304        }
305    }
306}
307
308/// Failure while constructing or presenting a heterogeneous frame.
309#[derive(Debug, Clone, Copy, PartialEq)]
310pub enum FrameComposerError {
311    /// The one frame clear color was not normalized linear RGBA.
312    InvalidBackground,
313    /// A target-composition opacity was non-finite or outside `0.0..=1.0`.
314    InvalidOpacity,
315    /// An image tint was not normalized linear RGBA.
316    InvalidTint,
317    /// An atlas source rectangle did not fit its image.
318    InvalidImageRegion,
319    /// A world image rectangle or pseudo-depth was invalid.
320    InvalidWorldImage,
321    /// Scalar endpoints were invalid or their finite subtraction overflowed.
322    InvalidValueRange {
323        /// Lower scalar endpoint supplied by the host.
324        minimum: f32,
325        /// Upper scalar endpoint supplied by the host.
326        maximum: f32,
327    },
328    /// A retained source belongs to another renderer or recovery generation.
329    RendererMismatch {
330        /// Category of the rejected retained source.
331        source: FrameSourceKind,
332    },
333    /// A frame-work limit would be exceeded.
334    BudgetExceeded {
335        /// Work category whose limit was exceeded.
336        resource: FrameBudgetResource,
337        /// Configured upper bound.
338        limit: usize,
339        /// Conservative work after accepting the requested item.
340        actual: usize,
341    },
342    /// CPU storage for frame construction could not be reserved.
343    AllocationFailed {
344        /// Minimum additional bytes requested by the failed reservation.
345        requested_bytes: usize,
346    },
347    /// Validation, surface acquisition, or GPU-capacity work failed.
348    Frame(RendererFrameError),
349}
350
351impl fmt::Display for FrameComposerError {
352    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
353        match self {
354            Self::InvalidBackground => write!(formatter, "frame background must be normalized"),
355            Self::InvalidOpacity => write!(formatter, "frame opacity must be finite and in 0..=1"),
356            Self::InvalidTint => write!(formatter, "frame image tint must be normalized"),
357            Self::InvalidImageRegion => write!(formatter, "frame image region is out of bounds"),
358            Self::InvalidWorldImage => {
359                write!(formatter, "frame world image rectangle or depth is invalid")
360            }
361            Self::InvalidValueRange { minimum, maximum } => {
362                write!(formatter, "invalid frame scalar range {minimum}..{maximum}")
363            }
364            Self::RendererMismatch { source } => {
365                write!(formatter, "frame {source:?} belongs to another renderer")
366            }
367            Self::BudgetExceeded {
368                resource,
369                limit,
370                actual,
371            } => write!(
372                formatter,
373                "frame {resource:?} work exceeds its limit {limit}: {actual}"
374            ),
375            Self::AllocationFailed { requested_bytes } => write!(
376                formatter,
377                "could not reserve {requested_bytes} additional bytes for frame construction"
378            ),
379            Self::Frame(error) => write!(formatter, "frame presentation failed: {error}"),
380        }
381    }
382}
383
384impl Error for FrameComposerError {}
385
386impl From<RendererFrameError> for FrameComposerError {
387    fn from(error: RendererFrameError) -> Self {
388        Self::Frame(error)
389    }
390}
391
392/// Bounded work and retained allocations referenced by one composed frame.
393#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
394pub struct FrameStatistics {
395    pass_count: usize,
396    command_count: usize,
397    vertex_count: usize,
398    streaming_vertex_count: usize,
399    reused_vertex_count: usize,
400    upload_bytes: usize,
401    streaming_upload_bytes: usize,
402    texture_bytes: usize,
403    retained_cpu_bytes: usize,
404    retained_buffer_bytes: usize,
405    draw_calls: usize,
406    source_counts: FrameSourceStatistics,
407}
408
409impl FrameStatistics {
410    /// Returns ordered source count.
411    pub const fn pass_count(self) -> usize {
412        self.pass_count
413    }
414
415    /// Returns referenced scene-command count.
416    pub const fn command_count(self) -> usize {
417        self.command_count
418    }
419
420    /// Returns referenced or generated vertex count.
421    pub const fn vertex_count(self) -> usize {
422        self.vertex_count
423    }
424
425    /// Returns streaming vertices selected by draws during this frame.
426    /// Repeated references may share one within-frame upload; use
427    /// [`Self::streaming_upload_bytes`] for the actual transferred payload.
428    pub const fn streaming_vertex_count(self) -> usize {
429        self.streaming_vertex_count
430    }
431
432    /// Returns retained prepared or dynamic vertices reused without frame upload.
433    pub const fn reused_vertex_count(self) -> usize {
434        self.reused_vertex_count
435    }
436
437    /// Returns bytes uploaded for streaming vertices and per-item uniforms.
438    pub const fn upload_bytes(self) -> usize {
439        self.upload_bytes
440    }
441
442    /// Returns the subset uploaded for streaming geometry or instances.
443    pub const fn streaming_upload_bytes(self) -> usize {
444        self.streaming_upload_bytes
445    }
446
447    /// Returns nominal retained texel-storage bytes referenced by frame items.
448    ///
449    /// Repeated image, scalar-field, and render-target identities are
450    /// deduplicated. Opaque backend alignment, tiling, page allocation, and
451    /// metadata are excluded because wgpu does not expose them. Color-map LUT
452    /// bytes follow the renderer's one-entry cache:
453    /// adjacent equal LUTs share one allocation, while an `A, B, A` sequence
454    /// keeps three views/allocations alive until submission.
455    pub const fn texture_bytes(self) -> usize {
456        self.texture_bytes
457    }
458
459    /// Returns CPU recovery or source bytes held by unique referenced resources.
460    ///
461    /// Drawing the same scene, buffer, image, atlas, or run more than once does
462    /// not multiply this value. Distinct retained resources are summed even when
463    /// their contents happen to be equal.
464    pub const fn retained_cpu_bytes(self) -> usize {
465        self.retained_cpu_bytes
466    }
467
468    /// Returns GPU vertex or instance-buffer bytes held by unique referenced resources.
469    pub const fn retained_buffer_bytes(self) -> usize {
470        self.retained_buffer_bytes
471    }
472
473    /// Returns the conservative number of scheduled draw calls.
474    pub const fn draw_calls(self) -> usize {
475        self.draw_calls
476    }
477
478    /// Returns accepted ordered inputs grouped by renderer source path.
479    pub const fn source_counts(self) -> FrameSourceStatistics {
480        self.source_counts
481    }
482
483    fn adding(self, other: Self) -> Self {
484        Self {
485            pass_count: self.pass_count.saturating_add(other.pass_count),
486            command_count: self.command_count.saturating_add(other.command_count),
487            vertex_count: self.vertex_count.saturating_add(other.vertex_count),
488            streaming_vertex_count: self
489                .streaming_vertex_count
490                .saturating_add(other.streaming_vertex_count),
491            reused_vertex_count: self
492                .reused_vertex_count
493                .saturating_add(other.reused_vertex_count),
494            upload_bytes: self.upload_bytes.saturating_add(other.upload_bytes),
495            streaming_upload_bytes: self
496                .streaming_upload_bytes
497                .saturating_add(other.streaming_upload_bytes),
498            texture_bytes: self.texture_bytes.saturating_add(other.texture_bytes),
499            retained_cpu_bytes: self
500                .retained_cpu_bytes
501                .saturating_add(other.retained_cpu_bytes),
502            retained_buffer_bytes: self
503                .retained_buffer_bytes
504                .saturating_add(other.retained_buffer_bytes),
505            draw_calls: self.draw_calls.saturating_add(other.draw_calls),
506            source_counts: self.source_counts.adding(other.source_counts),
507        }
508    }
509
510    fn without_uploads(mut self) -> Self {
511        self.upload_bytes = 0;
512        self.streaming_upload_bytes = 0;
513        self
514    }
515}
516
517/// Outcome and diagnostics for one composed frame.
518#[derive(Debug, Clone, Copy, PartialEq, Eq)]
519pub struct FrameReport {
520    status: RenderStatus,
521    statistics: FrameStatistics,
522    metrics: RendererFrameMetrics,
523    gpu_timing_id: Option<GpuTimingId>,
524}
525
526impl FrameReport {
527    /// Returns whether the frame was drawn or temporarily skipped.
528    pub const fn status(self) -> RenderStatus {
529        self.status
530    }
531
532    /// Returns bounded work referenced by the frame.
533    pub const fn statistics(self) -> FrameStatistics {
534        self.statistics
535    }
536
537    /// Returns CPU-side timing and tessellation diagnostics.
538    pub const fn metrics(self) -> RendererFrameMetrics {
539        self.metrics
540    }
541
542    /// Correlation key for this submitted pass's optional asynchronous GPU time.
543    /// Skipped frames never reserve a key. `None` also covers disabled/unavailable
544    /// timing or a full diagnostics ring; inspect renderer timing statistics.
545    pub const fn gpu_timing_id(self) -> Option<GpuTimingId> {
546        self.gpu_timing_id
547    }
548
549    /// Returns command encoders submitted by this composed frame.
550    pub const fn command_encoder_count(self) -> usize {
551        match self.status {
552            RenderStatus::Drawn => 1,
553            RenderStatus::Skipped(_) => 0,
554        }
555    }
556
557    /// Returns GPU render passes encoded by this composed frame.
558    pub const fn render_pass_count(self) -> usize {
559        match self.status {
560            RenderStatus::Drawn => 1,
561            RenderStatus::Skipped(_) => 0,
562        }
563    }
564
565    /// Returns queue submissions performed by this composed frame.
566    pub const fn queue_submission_count(self) -> usize {
567        match self.status {
568            RenderStatus::Drawn => 1,
569            RenderStatus::Skipped(_) => 0,
570        }
571    }
572
573    /// Returns surface presents performed by this composed frame.
574    pub const fn surface_present_count(self) -> usize {
575        match self.status {
576            RenderStatus::Drawn => 1,
577            RenderStatus::Skipped(_) => 0,
578        }
579    }
580}
581
582/// One bounded, stably ordered surface frame under construction.
583///
584/// Calling [`FrameComposer::present`] performs all fallible geometry and
585/// ownership validation before acquiring the surface. A successful frame uses
586/// one clear, one command encoder, one queue submission, and one present.
587#[must_use = "a frame composer does no rendering until present is called"]
588pub struct FrameComposer<'frame> {
589    renderer: &'frame mut WgpuRenderer,
590    background: Color,
591    budget: FrameBudget,
592    items: Vec<FrameItem<'frame>>,
593    retained_resources: Vec<RetainedResourceKey>,
594    scalar_luts: Vec<ScalarLutPlan>,
595    scalar_lut_upload_count: usize,
596    scalar_lut_allocation_count: usize,
597    planned: FrameStatistics,
598    next_insertion: usize,
599    cache: FrameCache,
600}
601
602impl Drop for FrameComposer<'_> {
603    fn drop(&mut self) {
604        self.cache.items = cache::recycle_items(std::mem::take(&mut self.items));
605        self.retained_resources.clear();
606        self.scalar_luts.clear();
607        self.cache.retained_resources = std::mem::take(&mut self.retained_resources);
608        self.cache.scalar_luts = std::mem::take(&mut self.scalar_luts);
609        self.cache.finish();
610        self.renderer.frame_cache = std::mem::take(&mut self.cache);
611    }
612}
613
614struct ScalarLutPlan {
615    sort_key: (i32, usize),
616    lut: [u8; COLOR_MAP_LUT_SIZE as usize * 4],
617}
618
619#[derive(Debug, Clone, Copy, PartialEq, Eq)]
620struct RetainedResourceKey {
621    address: usize,
622    class: u8,
623}
624
625#[derive(Debug, Clone, Copy)]
626struct RetainedResourceAccounting {
627    key: RetainedResourceKey,
628    cpu_bytes: usize,
629    buffer_bytes: usize,
630    texture_bytes: usize,
631}
632
633impl RetainedResourceAccounting {
634    const fn new(
635        key: RetainedResourceKey,
636        cpu_bytes: usize,
637        buffer_bytes: usize,
638        texture_bytes: usize,
639    ) -> Self {
640        Self {
641            key,
642            cpu_bytes,
643            buffer_bytes,
644            texture_bytes,
645        }
646    }
647}
648
649fn retained_key<T>(resource: &T, class: u8) -> RetainedResourceKey {
650    RetainedResourceKey {
651        address: std::ptr::from_ref(resource).cast::<()>() as usize,
652        class,
653    }
654}
655
656fn retained_arc_key<T>(resource: &Arc<T>, class: u8) -> RetainedResourceKey {
657    RetainedResourceKey {
658        address: Arc::as_ptr(resource).cast::<()>() as usize,
659        class,
660    }
661}
662
663fn account_new_retained_resources(
664    existing: &[RetainedResourceKey],
665    resources: &[RetainedResourceAccounting],
666    mut work: FrameStatistics,
667) -> (FrameStatistics, usize) {
668    let mut missing = 0usize;
669    for (index, resource) in resources.iter().enumerate() {
670        let already_in_request = resources[..index]
671            .iter()
672            .any(|previous| previous.key == resource.key);
673        if !already_in_request && !existing.contains(&resource.key) {
674            missing = missing.saturating_add(1);
675            work.retained_cpu_bytes = work.retained_cpu_bytes.saturating_add(resource.cpu_bytes);
676            work.retained_buffer_bytes = work
677                .retained_buffer_bytes
678                .saturating_add(resource.buffer_bytes);
679            work.texture_bytes = work.texture_bytes.saturating_add(resource.texture_bytes);
680        }
681    }
682    (work, missing)
683}
684
685fn scalar_lut_counts_with_inserted(
686    planned: &[ScalarLutPlan],
687    insertion: usize,
688    inserted: &[u8; COLOR_MAP_LUT_SIZE as usize * 4],
689    initial_cache: Option<&[u8; COLOR_MAP_LUT_SIZE as usize * 4]>,
690) -> (usize, usize) {
691    debug_assert!(insertion <= planned.len());
692    let mut previous: Option<&[u8; COLOR_MAP_LUT_SIZE as usize * 4]> = None;
693    let mut allocation_count = 0usize;
694    let mut first_matches_initial = false;
695    for merged_index in 0..=planned.len() {
696        let current = if merged_index == insertion {
697            inserted
698        } else {
699            let source_index = merged_index - usize::from(merged_index > insertion);
700            &planned[source_index].lut
701        };
702        if previous.is_none() {
703            first_matches_initial = initial_cache == Some(current);
704        }
705        if previous != Some(current) {
706            allocation_count = allocation_count.saturating_add(1);
707        }
708        previous = Some(current);
709    }
710    let upload_count = allocation_count.saturating_sub(usize::from(first_matches_initial));
711    (upload_count, allocation_count)
712}
713
714enum FrameItem<'frame> {
715    Scene {
716        scene: &'frame Scene,
717        camera: Camera2d,
718        options: FramePassOptions,
719        insertion: usize,
720    },
721    ScreenScene {
722        scene: &'frame ScreenScene,
723        options: FramePassOptions,
724        insertion: usize,
725    },
726    Prepared {
727        scene: &'frame PreparedScene,
728        camera: Camera2d,
729        options: FramePassOptions,
730        insertion: usize,
731    },
732    PreparedScreen {
733        scene: &'frame PreparedScreenScene,
734        options: FramePassOptions,
735        insertion: usize,
736    },
737    Dynamic {
738        mesh: &'frame DynamicMesh2d,
739        camera: Camera2d,
740        options: FramePassOptions,
741        insertion: usize,
742    },
743    Particle {
744        field: &'frame mut ParticleField2d,
745        camera: Camera2d,
746        options: FramePassOptions,
747        insertion: usize,
748    },
749    Scalar {
750        texture: &'frame ScalarFieldTexture,
751        color_map: &'frame ColorMap,
752        minimum: f32,
753        maximum: f32,
754        value_extent: f32,
755        sampling: ScalarFieldSampling,
756        options: FramePassOptions,
757        insertion: usize,
758    },
759    Image {
760        image: &'frame Image2d,
761        source: ImageTexelRect,
762        tint: Color,
763        sampling: ImageSampling,
764        options: FramePassOptions,
765        insertion: usize,
766    },
767    WorldImage {
768        image: &'frame Image2d,
769        source: ImageTexelRect,
770        rectangle: Rect,
771        depth: f32,
772        camera: Camera2d,
773        tint: Color,
774        sampling: ImageSampling,
775        options: FramePassOptions,
776        insertion: usize,
777    },
778    ImageBatch {
779        image: &'frame Image2d,
780        batch: &'frame ImageBatch2d,
781        placement: ImageBatchPlacement,
782        sampling: ImageSampling,
783        options: FramePassOptions,
784        insertion: usize,
785    },
786    Target {
787        target: &'frame RenderTarget2d,
788        blend_mode: BlendMode,
789        opacity: f32,
790        options: FramePassOptions,
791        insertion: usize,
792    },
793}
794
795impl FrameItem<'_> {
796    fn sort_key(&self) -> (i32, usize) {
797        match self {
798            Self::Scene {
799                options, insertion, ..
800            }
801            | Self::ScreenScene {
802                options, insertion, ..
803            }
804            | Self::Prepared {
805                options, insertion, ..
806            }
807            | Self::PreparedScreen {
808                options, insertion, ..
809            }
810            | Self::Dynamic {
811                options, insertion, ..
812            }
813            | Self::Particle {
814                options, insertion, ..
815            }
816            | Self::Scalar {
817                options, insertion, ..
818            }
819            | Self::Image {
820                options, insertion, ..
821            }
822            | Self::WorldImage {
823                options, insertion, ..
824            }
825            | Self::ImageBatch {
826                options, insertion, ..
827            }
828            | Self::Target {
829                options, insertion, ..
830            } => (options.order(), *insertion),
831        }
832    }
833}
834
835impl WgpuRenderer {
836    /// Begins one bounded heterogeneous frame with a single clear color.
837    pub fn begin_frame(
838        &mut self,
839        background: Color,
840        budget: FrameBudget,
841    ) -> Result<FrameComposer<'_>, FrameComposerError> {
842        if !background.is_normalized() {
843            return Err(FrameComposerError::InvalidBackground);
844        }
845        let mut cache = std::mem::take(&mut self.frame_cache);
846        cache.begin();
847        let items = std::mem::take(&mut cache.items);
848        let retained_resources = std::mem::take(&mut cache.retained_resources);
849        let scalar_luts = std::mem::take(&mut cache.scalar_luts);
850        Ok(FrameComposer {
851            renderer: self,
852            background,
853            budget,
854            items,
855            retained_resources,
856            scalar_luts,
857            scalar_lut_upload_count: 0,
858            scalar_lut_allocation_count: 0,
859            planned: FrameStatistics::default(),
860            next_insertion: 0,
861            cache,
862        })
863    }
864}
865
866#[derive(Debug, Clone, Copy)]
867struct ResolvedViewport {
868    viewport: LogicalViewport,
869    origin: Vec2,
870    scissor: ScissorRect,
871    item_clip: Option<ScissorRect>,
872    item_clipped_out: bool,
873}
874
875enum ReadySource<'frame> {
876    Streaming,
877    Prepared(&'frame wgpu::Buffer),
878    Dynamic(&'frame wgpu::Buffer),
879}
880
881struct ReadyGeometry<'frame> {
882    source: ReadySource<'frame>,
883    vertex_count: usize,
884    batches: Vec<PreparedDrawBatch>,
885    camera_uniform: CameraUniform,
886    viewport: ResolvedViewport,
887}
888
889enum ReadyItem<'frame> {
890    Geometry(ReadyGeometry<'frame>),
891    Particle {
892        field: &'frame mut ParticleField2d,
893        visible_count: usize,
894        pending_statistics: ParticleStatistics,
895        initial_cpu_allocation_bytes: usize,
896        camera_uniform: CameraUniform,
897        viewport: ResolvedViewport,
898    },
899    Scalar {
900        texture: &'frame ScalarFieldTexture,
901        color_map: &'frame ColorMap,
902        uniform: HeatmapUniform,
903        viewport: ResolvedViewport,
904    },
905    Image {
906        image: &'frame Image2d,
907        sampling: ImageSampling,
908        uniform: ImageUniform,
909        viewport: ResolvedViewport,
910    },
911    ImageBatch {
912        image: &'frame Image2d,
913        batch: &'frame ImageBatch2d,
914        sampling: ImageSampling,
915        uniform: ImageUniform,
916        viewport: ResolvedViewport,
917    },
918    Target {
919        target: &'frame RenderTarget2d,
920        blend_mode: BlendMode,
921        uniform: CompositeUniform,
922        viewport: ResolvedViewport,
923    },
924}
925
926#[derive(Clone)]
927struct FrameBinding {
928    _buffer: wgpu::Buffer,
929    bind_group: wgpu::BindGroup,
930}
931
932fn preflight_frame_items(
933    renderer: &WgpuRenderer,
934    target_viewport: LogicalViewport,
935    items: &[FrameItem<'_>],
936) -> Result<(), FrameComposerError> {
937    for item in items {
938        match item {
939            FrameItem::Scene {
940                camera, options, ..
941            } => {
942                let viewport = resolve_viewport(renderer, target_viewport, *options)?;
943                CameraUniform::new_in_region(
944                    *camera,
945                    viewport.viewport,
946                    viewport.origin,
947                    target_viewport,
948                )
949                .ok_or(RendererFrameError::InvalidGeometryTransform)?;
950            }
951            FrameItem::ScreenScene { options, .. } => {
952                let viewport = resolve_viewport(renderer, target_viewport, *options)?;
953                let camera = screen_camera(viewport.viewport)
954                    .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
955                CameraUniform::new_in_region(
956                    camera,
957                    viewport.viewport,
958                    viewport.origin,
959                    target_viewport,
960                )
961                .ok_or(RendererFrameError::InvalidGeometryTransform)?;
962            }
963            FrameItem::Prepared {
964                scene,
965                camera,
966                options,
967                ..
968            } => {
969                let viewport = resolve_viewport(renderer, target_viewport, *options)?;
970                let uniform = CameraUniform::new_in_region(
971                    *camera,
972                    viewport.viewport,
973                    viewport.origin,
974                    target_viewport,
975                )
976                .ok_or(RendererFrameError::InvalidGeometryTransform)?;
977                if !geometry_is_safe_for_cached(
978                    Some(&scene.geometry_validation_cache),
979                    scene.geometry_extents,
980                    GeometryValidationSource::Tessellated(&scene.vertices),
981                    uniform,
982                ) {
983                    return Err(RendererFrameError::InvalidGeometryTransform.into());
984                }
985            }
986            FrameItem::PreparedScreen { scene, options, .. } => {
987                let viewport = resolve_viewport(renderer, target_viewport, *options)?;
988                let camera = screen_camera(viewport.viewport)
989                    .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
990                let uniform = CameraUniform::new_in_region(
991                    camera,
992                    viewport.viewport,
993                    viewport.origin,
994                    target_viewport,
995                )
996                .ok_or(RendererFrameError::InvalidGeometryTransform)?;
997                if !geometry_is_safe_for_cached(
998                    Some(&scene.scene.geometry_validation_cache),
999                    scene.scene.geometry_extents,
1000                    GeometryValidationSource::Tessellated(&scene.scene.vertices),
1001                    uniform,
1002                ) {
1003                    return Err(RendererFrameError::InvalidGeometryTransform.into());
1004                }
1005            }
1006            FrameItem::Dynamic {
1007                mesh,
1008                camera,
1009                options,
1010                ..
1011            } => {
1012                let viewport = resolve_viewport(renderer, target_viewport, *options)?;
1013                let uniform = CameraUniform::new_in_region(
1014                    *camera,
1015                    viewport.viewport,
1016                    viewport.origin,
1017                    target_viewport,
1018                )
1019                .ok_or(RendererFrameError::InvalidGeometryTransform)?;
1020                if !geometry_is_safe_for_cached(
1021                    Some(&mesh.geometry_validation_cache),
1022                    mesh.geometry_extents,
1023                    GeometryValidationSource::Dynamic(&mesh.vertices),
1024                    uniform,
1025                ) {
1026                    return Err(RendererFrameError::InvalidGeometryTransform.into());
1027                }
1028            }
1029            FrameItem::Particle {
1030                camera, options, ..
1031            } => {
1032                let viewport = resolve_viewport(renderer, target_viewport, *options)?;
1033                CameraUniform::new(*camera, viewport.viewport)
1034                    .ok_or(RendererFrameError::InvalidGeometryTransform)?;
1035                CameraUniform::new_in_region(
1036                    *camera,
1037                    viewport.viewport,
1038                    viewport.origin,
1039                    target_viewport,
1040                )
1041                .ok_or(RendererFrameError::InvalidGeometryTransform)?;
1042            }
1043            FrameItem::Scalar {
1044                texture,
1045                minimum,
1046                maximum,
1047                value_extent,
1048                sampling,
1049                options,
1050                ..
1051            } => {
1052                if !scalar_normalization_is_portable(texture, *minimum, *value_extent) {
1053                    return Err(FrameComposerError::InvalidValueRange {
1054                        minimum: *minimum,
1055                        maximum: *maximum,
1056                    });
1057                }
1058                let viewport = resolve_viewport(renderer, target_viewport, *options)?;
1059                let region = LogicalViewportRegion::new(
1060                    LogicalScreenPosition::from_vec2(viewport.origin),
1061                    viewport.viewport,
1062                )
1063                .map_err(|_| RendererFrameError::InvalidViewport)?;
1064                HeatmapUniform::new(
1065                    *minimum,
1066                    *value_extent,
1067                    texture.width(),
1068                    texture.height(),
1069                    *sampling,
1070                )
1071                .in_region(region, target_viewport)
1072                .ok_or(RendererFrameError::InvalidGeometryTransform)?;
1073            }
1074            FrameItem::Image { options, .. } => {
1075                let viewport = resolve_viewport(renderer, target_viewport, *options)?;
1076                let region = LogicalViewportRegion::new(
1077                    LogicalScreenPosition::from_vec2(viewport.origin),
1078                    viewport.viewport,
1079                )
1080                .map_err(|_| RendererFrameError::InvalidViewport)?;
1081                CompositeUniform::in_region(1.0, region, target_viewport)
1082                    .ok_or(RendererFrameError::InvalidGeometryTransform)?;
1083            }
1084            FrameItem::Target {
1085                opacity, options, ..
1086            } => {
1087                let viewport = resolve_viewport(renderer, target_viewport, *options)?;
1088                let region = LogicalViewportRegion::new(
1089                    LogicalScreenPosition::from_vec2(viewport.origin),
1090                    viewport.viewport,
1091                )
1092                .map_err(|_| RendererFrameError::InvalidViewport)?;
1093                CompositeUniform::in_region(*opacity, region, target_viewport)
1094                    .ok_or(RendererFrameError::InvalidGeometryTransform)?;
1095            }
1096            FrameItem::WorldImage {
1097                rectangle,
1098                depth,
1099                camera,
1100                options,
1101                ..
1102            } => {
1103                let viewport = resolve_viewport(renderer, target_viewport, *options)?;
1104                let camera_uniform = CameraUniform::new_in_region(
1105                    *camera,
1106                    viewport.viewport,
1107                    viewport.origin,
1108                    target_viewport,
1109                )
1110                .ok_or(RendererFrameError::InvalidGeometryTransform)?;
1111                let minimum = rectangle.min();
1112                let maximum = rectangle.max();
1113                for world in [
1114                    Vec2::new(minimum.x, maximum.y),
1115                    maximum,
1116                    minimum,
1117                    Vec2::new(maximum.x, minimum.y),
1118                ] {
1119                    let screen = camera_uniform.world_to_screen(world, *depth);
1120                    let clip = Vec2::new(
1121                        screen.x.mul_add(
1122                            camera_uniform.screen_to_clip[0],
1123                            camera_uniform.screen_to_clip[2],
1124                        ),
1125                        screen.y.mul_add(
1126                            camera_uniform.screen_to_clip[1],
1127                            camera_uniform.screen_to_clip[3],
1128                        ),
1129                    );
1130                    if ![clip.x, clip.y].into_iter().all(is_portable_shader_source) {
1131                        return Err(RendererFrameError::InvalidGeometryTransform.into());
1132                    }
1133                }
1134            }
1135            FrameItem::ImageBatch {
1136                batch,
1137                options,
1138                placement,
1139                ..
1140            } => {
1141                let viewport = resolve_viewport(renderer, target_viewport, *options)?;
1142                let uniform = image::batch_uniform(target_viewport, viewport.origin, *placement)?;
1143                if !batch.sprites_are_safe_for_target(
1144                    Vec2::new(uniform.uv_rect[0], uniform.uv_rect[1]),
1145                    uniform.destination,
1146                ) {
1147                    return Err(RendererFrameError::InvalidGeometryTransform.into());
1148                }
1149            }
1150        }
1151    }
1152    Ok(())
1153}
1154
1155#[cfg(test)]
1156fn image_sprites_are_safe_for_target(
1157    sprites: &[ImageSprite2d],
1158    viewport_origin: Vec2,
1159    clip_transform: [f32; 4],
1160) -> bool {
1161    image::sprites_are_safe_for_target(sprites, viewport_origin, clip_transform)
1162}
1163
1164fn set_particle_rendered(items: &mut [ReadyItem<'_>], presented: bool) {
1165    for item in items {
1166        if let ReadyItem::Particle {
1167            field,
1168            visible_count,
1169            pending_statistics,
1170            viewport,
1171            ..
1172        } = item
1173        {
1174            field.statistics = ParticleStatistics {
1175                rendered: if presented && !viewport.item_clipped_out {
1176                    *visible_count
1177                } else {
1178                    0
1179                },
1180                ..*pending_statistics
1181            };
1182        }
1183    }
1184}
1185
1186#[allow(clippy::too_many_arguments)]
1187fn prepare_particle_item<'frame>(
1188    field: &'frame mut ParticleField2d,
1189    camera: Camera2d,
1190    viewport: ResolvedViewport,
1191    target_viewport: LogicalViewport,
1192    ready: &mut Vec<ReadyItem<'frame>>,
1193    statistics: &mut FrameStatistics,
1194) -> Result<(), FrameComposerError> {
1195    let initial_cpu_allocation_bytes = field.cpu_allocation_bytes();
1196    let local_uniform = CameraUniform::new(camera, viewport.viewport)
1197        .ok_or(RendererFrameError::InvalidGeometryTransform)?;
1198    let target_uniform =
1199        CameraUniform::new_in_region(camera, viewport.viewport, viewport.origin, target_viewport)
1200            .ok_or(RendererFrameError::InvalidGeometryTransform)?;
1201    let instance_count = field.instances.len();
1202    let visibility_checked = instance_count.min(field.budget.max_visibility_checks_per_frame);
1203
1204    let (visible_count, selected_count) = if visibility_checked < instance_count {
1205        field.visible_instances.clear();
1206        validate_particle_staging_capacity(&field.visible_instances, visibility_checked)?;
1207        for candidate_index in 0..visibility_checked {
1208            let source_index =
1209                uniformly_sampled_index(candidate_index, instance_count, visibility_checked);
1210            let instance = field.instances[source_index];
1211            if !instance.is_safe_for(target_uniform, target_viewport) {
1212                return Err(RendererFrameError::InvalidGeometryTransform.into());
1213            }
1214            let Some(intersects) =
1215                instance.validated_viewport_intersection(local_uniform, viewport.viewport)
1216            else {
1217                return Err(RendererFrameError::InvalidGeometryTransform.into());
1218            };
1219            if intersects {
1220                field.visible_instances.push(instance);
1221            }
1222        }
1223        let visible_count = field.visible_instances.len();
1224        let selected_count = visible_count.min(field.budget.instance_limit());
1225        if selected_count < visible_count {
1226            let mut visible_index = 0;
1227            field.visible_instances.retain(|_| {
1228                let selected = particle_visible_index_is_selected(
1229                    visible_index,
1230                    visible_count,
1231                    selected_count,
1232                );
1233                visible_index += 1;
1234                selected
1235            });
1236        }
1237        (visible_count, selected_count)
1238    } else {
1239        let visible_count = visible_particle_count_for_frame(
1240            &field.instances,
1241            local_uniform,
1242            target_uniform,
1243            viewport.viewport,
1244            target_viewport,
1245        )?;
1246        let selected_count = visible_count.min(field.budget.instance_limit());
1247        if selected_count == field.instances.len() {
1248            field.visible_instances.clear();
1249        } else {
1250            field.visible_instances.clear();
1251            validate_particle_staging_capacity(&field.visible_instances, selected_count)?;
1252            let mut visible_index = 0;
1253            for instance in field.instances.iter().copied() {
1254                if !instance.intersects_viewport(local_uniform, viewport.viewport) {
1255                    continue;
1256                }
1257                let selected_index = field.visible_instances.len();
1258                if selected_index < selected_count
1259                    && particle_visible_index_is_selected(
1260                        visible_index,
1261                        visible_count,
1262                        selected_count,
1263                    )
1264                {
1265                    field.visible_instances.push(instance);
1266                }
1267                visible_index += 1;
1268            }
1269        }
1270        (visible_count, selected_count)
1271    };
1272    let pending_statistics = particle_statistics_with_budget(
1273        instance_count,
1274        visibility_checked,
1275        visible_count,
1276        selected_count,
1277        0,
1278    );
1279    *statistics = statistics.adding(FrameStatistics {
1280        pass_count: 1,
1281        command_count: usize::from(instance_count > 0),
1282        vertex_count: selected_count.saturating_mul(6),
1283        streaming_vertex_count: selected_count.saturating_mul(6),
1284        reused_vertex_count: 0,
1285        upload_bytes: selected_count
1286            .saturating_mul(std::mem::size_of::<ParticleGpu>())
1287            .saturating_add(std::mem::size_of::<CameraUniform>()),
1288        streaming_upload_bytes: selected_count.saturating_mul(std::mem::size_of::<ParticleGpu>()),
1289        texture_bytes: 0,
1290        retained_cpu_bytes: 0,
1291        retained_buffer_bytes: 0,
1292        draw_calls: usize::from(selected_count > 0),
1293        source_counts: FrameSourceStatistics::default(),
1294    });
1295    ready.push(ReadyItem::Particle {
1296        field,
1297        visible_count: selected_count,
1298        pending_statistics,
1299        initial_cpu_allocation_bytes,
1300        camera_uniform: target_uniform,
1301        viewport,
1302    });
1303    Ok(())
1304}
1305
1306fn visible_particle_count_for_frame(
1307    instances: &[ParticleGpu],
1308    local_camera: CameraUniform,
1309    target_camera: CameraUniform,
1310    viewport: LogicalViewport,
1311    target_viewport: LogicalViewport,
1312) -> Result<usize, RendererFrameError> {
1313    let mut visible = 0;
1314    for instance in instances {
1315        let Some(intersects) = instance.validated_viewport_intersection(local_camera, viewport)
1316        else {
1317            return Err(RendererFrameError::InvalidGeometryTransform);
1318        };
1319        if !instance.is_safe_for(target_camera, target_viewport) {
1320            return Err(RendererFrameError::InvalidGeometryTransform);
1321        }
1322        visible += usize::from(intersects);
1323    }
1324    Ok(visible)
1325}
1326
1327// Keep grown scratch reachable on every structured failure, both for reuse
1328// and for the cache's conservative owned-capacity peak accounting.
1329fn with_streaming_batches(
1330    pool: &mut Vec<Vec<PreparedDrawBatch>>,
1331    prepare: impl FnOnce(&mut Vec<PreparedDrawBatch>) -> Result<(), FrameComposerError>,
1332) -> Result<(), FrameComposerError> {
1333    let mut batches = pool.pop().unwrap_or_default();
1334    let result = prepare(&mut batches);
1335    if batches.capacity() > 0 {
1336        batches.clear();
1337        pool.push(batches);
1338    }
1339    result
1340}
1341
1342#[allow(clippy::too_many_arguments)]
1343fn prepare_streaming_scene<'frame>(
1344    scene: &'frame Scene,
1345    camera: Camera2d,
1346    options: FramePassOptions,
1347    renderer: &WgpuRenderer,
1348    target_viewport: LogicalViewport,
1349    streaming_vertices: &mut Vec<Vertex>,
1350    ready: &mut Vec<ReadyItem<'frame>>,
1351    statistics: &mut FrameStatistics,
1352    aggregate: &mut TessellationStats,
1353    batches: &mut Vec<PreparedDrawBatch>,
1354    proofs: &mut streaming::StreamingSceneProofs<'frame>,
1355) -> Result<(), FrameComposerError> {
1356    let viewport = resolve_viewport(renderer, target_viewport, options)?;
1357    let camera_uniform =
1358        CameraUniform::new_in_region(camera, viewport.viewport, viewport.origin, target_viewport)
1359            .ok_or(RendererFrameError::InvalidGeometryTransform)?;
1360    if !scene_estimate_fits_streaming_device(
1361        scene,
1362        &renderer.device,
1363        streaming_vertices.len(),
1364        renderer.vertex_capacity,
1365    ) {
1366        return Err(RendererFrameError::GeometryCapacityTooLarge.into());
1367    }
1368    proofs.prepare(
1369        scene,
1370        camera_uniform,
1371        viewport,
1372        streaming_vertices,
1373        ready,
1374        statistics,
1375        aggregate,
1376        batches,
1377    )
1378}
1379
1380#[allow(clippy::too_many_arguments)]
1381fn prepare_streaming_scene_resolved<'frame>(
1382    scene: &Scene,
1383    camera_uniform: CameraUniform,
1384    viewport: ResolvedViewport,
1385    streaming_vertices: &mut Vec<Vertex>,
1386    ready: &mut Vec<ReadyItem<'frame>>,
1387    statistics: &mut FrameStatistics,
1388    aggregate: &mut TessellationStats,
1389    batches: &mut Vec<PreparedDrawBatch>,
1390) -> Result<(), FrameComposerError> {
1391    let vertex_start = streaming_vertices.len();
1392    let stats =
1393        tessellate_scene(scene, streaming_vertices, batches).map_err(RendererFrameError::from)?;
1394    let vertices = &streaming_vertices[vertex_start..];
1395    let extents = GeometryExtents::from_vertices(vertices);
1396    if !geometry_is_safe_for(
1397        extents,
1398        GeometryValidationSource::Tessellated(vertices),
1399        camera_uniform,
1400    ) {
1401        streaming_vertices.truncate(vertex_start);
1402        return Err(RendererFrameError::InvalidGeometryTransform.into());
1403    }
1404    *statistics = statistics.adding(FrameStatistics {
1405        pass_count: 1,
1406        command_count: scene.command_count(),
1407        vertex_count: stats.vertex_count,
1408        streaming_vertex_count: stats.vertex_count,
1409        reused_vertex_count: 0,
1410        upload_bytes: stats
1411            .upload_bytes
1412            .saturating_add(std::mem::size_of::<CameraUniform>()),
1413        streaming_upload_bytes: stats.upload_bytes,
1414        texture_bytes: 0,
1415        retained_cpu_bytes: 0,
1416        retained_buffer_bytes: 0,
1417        draw_calls: batches.len(),
1418        source_counts: FrameSourceStatistics::default(),
1419    });
1420    add_tessellation_stats(aggregate, stats);
1421    ready.push(ReadyItem::Geometry(ReadyGeometry {
1422        source: ReadySource::Streaming,
1423        vertex_count: vertices.len(),
1424        batches: std::mem::take(batches),
1425        camera_uniform,
1426        viewport,
1427    }));
1428    Ok(())
1429}
1430
1431#[allow(clippy::too_many_arguments)]
1432fn prepare_retained_geometry<'frame>(
1433    source: ReadySource<'frame>,
1434    vertex_count: usize,
1435    extents: GeometryExtents,
1436    geometry_validation: GeometryValidationSource<'_>,
1437    geometry_validation_cache: Option<&GeometryValidationCache>,
1438    batches: &[PreparedDrawBatch],
1439    command_count: usize,
1440    source_stats: TessellationStats,
1441    camera: Camera2d,
1442    viewport: ResolvedViewport,
1443    target_viewport: LogicalViewport,
1444    ready: &mut Vec<ReadyItem<'frame>>,
1445    statistics: &mut FrameStatistics,
1446    aggregate: &mut TessellationStats,
1447    mut owned_batches: Vec<PreparedDrawBatch>,
1448) -> Result<(), FrameComposerError> {
1449    let camera_uniform =
1450        CameraUniform::new_in_region(camera, viewport.viewport, viewport.origin, target_viewport)
1451            .ok_or(RendererFrameError::InvalidGeometryTransform)?;
1452    if !geometry_is_safe_for_cached(
1453        geometry_validation_cache,
1454        extents,
1455        geometry_validation,
1456        camera_uniform,
1457    ) {
1458        return Err(RendererFrameError::InvalidGeometryTransform.into());
1459    }
1460    owned_batches
1461        .try_reserve(batches.len())
1462        .map_err(|_| FrameComposerError::AllocationFailed {
1463            requested_bytes: batches
1464                .len()
1465                .saturating_mul(std::mem::size_of::<PreparedDrawBatch>()),
1466        })?;
1467    owned_batches.extend_from_slice(batches);
1468    *statistics = statistics.adding(FrameStatistics {
1469        pass_count: 1,
1470        command_count,
1471        vertex_count,
1472        streaming_vertex_count: 0,
1473        reused_vertex_count: vertex_count,
1474        upload_bytes: std::mem::size_of::<CameraUniform>(),
1475        streaming_upload_bytes: 0,
1476        texture_bytes: 0,
1477        retained_cpu_bytes: 0,
1478        retained_buffer_bytes: 0,
1479        draw_calls: owned_batches.len(),
1480        source_counts: FrameSourceStatistics::default(),
1481    });
1482    add_tessellation_stats(aggregate, source_stats);
1483    ready.push(ReadyItem::Geometry(ReadyGeometry {
1484        source,
1485        vertex_count,
1486        batches: owned_batches,
1487        camera_uniform,
1488        viewport,
1489    }));
1490    Ok(())
1491}
1492
1493fn resolve_viewport(
1494    renderer: &WgpuRenderer,
1495    target: LogicalViewport,
1496    options: FramePassOptions,
1497) -> Result<ResolvedViewport, FrameComposerError> {
1498    let (viewport, origin) = match options.viewport() {
1499        Some(region) => (region.viewport(), region.origin().to_vec2()),
1500        None => (target, Vec2::ZERO),
1501    };
1502    let max = origin + viewport.size();
1503    if !origin.is_finite()
1504        || !max.is_finite()
1505        || origin.x < 0.0
1506        || origin.y < 0.0
1507        || max.x > target.width()
1508        || max.y > target.height()
1509    {
1510        return Err(RendererFrameError::InvalidViewport.into());
1511    }
1512    let scissor = logical_viewport_scissor(
1513        origin,
1514        viewport,
1515        renderer.scale_factor as f32,
1516        renderer.config.width,
1517        renderer.config.height,
1518    )
1519    .ok_or(RendererFrameError::InvalidViewport)?;
1520    let (item_clip, item_clipped_out) = match options.clip() {
1521        Some(clip) => {
1522            let resolved = screen_clip_to_scissor(clip, viewport, renderer.scale_factor as f32)
1523                .and_then(|clip| offset_scissor(clip, scissor));
1524            (resolved, resolved.is_none())
1525        }
1526        None => (None, false),
1527    };
1528    Ok(ResolvedViewport {
1529        viewport,
1530        origin,
1531        scissor,
1532        item_clip,
1533        item_clipped_out,
1534    })
1535}
1536
1537fn create_frame_binding(renderer: &mut WgpuRenderer, item: &ReadyItem<'_>) -> FrameBinding {
1538    match item {
1539        ReadyItem::Geometry(geometry) => create_camera_binding(renderer, &geometry.camera_uniform),
1540        ReadyItem::Particle { camera_uniform, .. } => {
1541            create_camera_binding(renderer, camera_uniform)
1542        }
1543        ReadyItem::Scalar {
1544            texture,
1545            color_map,
1546            uniform,
1547            ..
1548        } => {
1549            let color_map_view = renderer.color_map_view(color_map);
1550            let scalar_view = texture
1551                .texture
1552                .create_view(&wgpu::TextureViewDescriptor::default());
1553            let bytes = bytemuck::bytes_of(uniform);
1554            let buffer = renderer.device.create_buffer(&wgpu::BufferDescriptor {
1555                label: Some("sim-engine frame heatmap uniform"),
1556                size: bytes.len() as wgpu::BufferAddress,
1557                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1558                mapped_at_creation: false,
1559            });
1560            renderer.queue.write_buffer(&buffer, 0, bytes);
1561            let bind_group = renderer
1562                .device
1563                .create_bind_group(&wgpu::BindGroupDescriptor {
1564                    label: Some("sim-engine frame heatmap bind group"),
1565                    layout: &renderer.heatmap_bind_group_layout,
1566                    entries: &[
1567                        wgpu::BindGroupEntry {
1568                            binding: 0,
1569                            resource: wgpu::BindingResource::TextureView(&scalar_view),
1570                        },
1571                        wgpu::BindGroupEntry {
1572                            binding: 1,
1573                            resource: wgpu::BindingResource::TextureView(&color_map_view),
1574                        },
1575                        wgpu::BindGroupEntry {
1576                            binding: 2,
1577                            resource: buffer.as_entire_binding(),
1578                        },
1579                    ],
1580                });
1581            FrameBinding {
1582                _buffer: buffer,
1583                bind_group,
1584            }
1585        }
1586        ReadyItem::Image {
1587            image,
1588            sampling,
1589            uniform,
1590            ..
1591        }
1592        | ReadyItem::ImageBatch {
1593            image,
1594            sampling,
1595            uniform,
1596            ..
1597        } => {
1598            let bytes = bytemuck::bytes_of(uniform);
1599            let buffer = renderer.device.create_buffer(&wgpu::BufferDescriptor {
1600                label: Some("sim-engine frame image uniform"),
1601                size: bytes.len() as wgpu::BufferAddress,
1602                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1603                mapped_at_creation: false,
1604            });
1605            renderer.queue.write_buffer(&buffer, 0, bytes);
1606            let bind_group = renderer
1607                .device
1608                .create_bind_group(&wgpu::BindGroupDescriptor {
1609                    label: Some("sim-engine frame image bind group"),
1610                    layout: &renderer.image_renderer.bind_group_layout,
1611                    entries: &[
1612                        wgpu::BindGroupEntry {
1613                            binding: 0,
1614                            resource: wgpu::BindingResource::TextureView(&image.view),
1615                        },
1616                        wgpu::BindGroupEntry {
1617                            binding: 1,
1618                            resource: wgpu::BindingResource::Sampler(
1619                                renderer.image_renderer.sampler(*sampling),
1620                            ),
1621                        },
1622                        wgpu::BindGroupEntry {
1623                            binding: 2,
1624                            resource: buffer.as_entire_binding(),
1625                        },
1626                    ],
1627                });
1628            FrameBinding {
1629                _buffer: buffer,
1630                bind_group,
1631            }
1632        }
1633        ReadyItem::Target {
1634            target, uniform, ..
1635        } => {
1636            let bytes = bytemuck::bytes_of(uniform);
1637            let buffer = renderer.device.create_buffer(&wgpu::BufferDescriptor {
1638                label: Some("sim-engine frame composition uniform"),
1639                size: bytes.len() as wgpu::BufferAddress,
1640                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1641                mapped_at_creation: false,
1642            });
1643            renderer.queue.write_buffer(&buffer, 0, bytes);
1644            let bind_group = renderer
1645                .device
1646                .create_bind_group(&wgpu::BindGroupDescriptor {
1647                    label: Some("sim-engine frame composition bind group"),
1648                    layout: &renderer.composition_pipelines.bind_group_layout,
1649                    entries: &[
1650                        wgpu::BindGroupEntry {
1651                            binding: 0,
1652                            resource: wgpu::BindingResource::TextureView(&target.view),
1653                        },
1654                        wgpu::BindGroupEntry {
1655                            binding: 1,
1656                            resource: buffer.as_entire_binding(),
1657                        },
1658                    ],
1659                });
1660            FrameBinding {
1661                _buffer: buffer,
1662                bind_group,
1663            }
1664        }
1665    }
1666}
1667
1668fn ready_uniform_bytes(item: &ReadyItem<'_>) -> usize {
1669    match item {
1670        ReadyItem::Geometry(_) | ReadyItem::Particle { .. } => std::mem::size_of::<CameraUniform>(),
1671        ReadyItem::Scalar { .. } => std::mem::size_of::<HeatmapUniform>(),
1672        ReadyItem::Image { .. } | ReadyItem::ImageBatch { .. } => {
1673            std::mem::size_of::<ImageUniform>()
1674        }
1675        ReadyItem::Target { .. } => std::mem::size_of::<CompositeUniform>(),
1676    }
1677}
1678
1679fn create_camera_binding(renderer: &WgpuRenderer, uniform: &CameraUniform) -> FrameBinding {
1680    let label = "sim-engine frame camera uniform";
1681    let bytes = bytemuck::bytes_of(uniform);
1682    let buffer = renderer.device.create_buffer(&wgpu::BufferDescriptor {
1683        label: Some(label),
1684        size: bytes.len() as wgpu::BufferAddress,
1685        usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
1686        mapped_at_creation: false,
1687    });
1688    renderer.queue.write_buffer(&buffer, 0, bytes);
1689    let bind_group = renderer
1690        .device
1691        .create_bind_group(&wgpu::BindGroupDescriptor {
1692            label: Some("sim-engine frame camera bind group"),
1693            layout: &renderer.camera_bind_group_layout,
1694            entries: &[wgpu::BindGroupEntry {
1695                binding: 0,
1696                resource: buffer.as_entire_binding(),
1697            }],
1698        });
1699    FrameBinding {
1700        _buffer: buffer,
1701        bind_group,
1702    }
1703}
1704
1705fn effective_scissor(
1706    viewport: ResolvedViewport,
1707    source_clip: Option<ScreenClipRect>,
1708    scale_factor: f32,
1709) -> Option<ScissorRect> {
1710    if viewport.item_clipped_out {
1711        return None;
1712    }
1713    let source = match source_clip {
1714        Some(clip) => screen_clip_to_scissor(clip, viewport.viewport, scale_factor)
1715            .and_then(|clip| offset_scissor(clip, viewport.scissor))?,
1716        None => viewport.scissor,
1717    };
1718    match viewport.item_clip {
1719        Some(item) => intersect_scissors(source, item),
1720        None => Some(source),
1721    }
1722}
1723
1724fn intersect_scissors(first: ScissorRect, second: ScissorRect) -> Option<ScissorRect> {
1725    let x = first.x.max(second.x);
1726    let y = first.y.max(second.y);
1727    let max_x = first
1728        .x
1729        .saturating_add(first.width)
1730        .min(second.x.saturating_add(second.width));
1731    let max_y = first
1732        .y
1733        .saturating_add(first.height)
1734        .min(second.y.saturating_add(second.height));
1735    (max_x > x && max_y > y).then_some(ScissorRect {
1736        x,
1737        y,
1738        width: max_x - x,
1739        height: max_y - y,
1740    })
1741}
1742
1743fn validate_frame_budget(
1744    budget: FrameBudget,
1745    statistics: FrameStatistics,
1746) -> Result<(), FrameComposerError> {
1747    let work = [
1748        (
1749            FrameBudgetResource::Passes,
1750            budget.max_passes,
1751            statistics.pass_count,
1752        ),
1753        (
1754            FrameBudgetResource::Commands,
1755            budget.max_commands,
1756            statistics.command_count,
1757        ),
1758        (
1759            FrameBudgetResource::Vertices,
1760            budget.max_vertices,
1761            statistics.vertex_count,
1762        ),
1763        (
1764            FrameBudgetResource::UploadBytes,
1765            budget.max_upload_bytes,
1766            statistics.upload_bytes,
1767        ),
1768        (
1769            FrameBudgetResource::TextureBytes,
1770            budget.max_texture_bytes,
1771            statistics.texture_bytes,
1772        ),
1773        (
1774            FrameBudgetResource::DrawCalls,
1775            budget.max_draw_calls,
1776            statistics.draw_calls,
1777        ),
1778    ];
1779    for (resource, limit, actual) in work {
1780        if actual > limit {
1781            return Err(FrameComposerError::BudgetExceeded {
1782                resource,
1783                limit,
1784                actual,
1785            });
1786        }
1787    }
1788    Ok(())
1789}
1790
1791fn add_tessellation_stats(aggregate: &mut TessellationStats, source: TessellationStats) {
1792    aggregate.command_count = aggregate.command_count.saturating_add(source.command_count);
1793    aggregate.rendered_command_count = aggregate
1794        .rendered_command_count
1795        .saturating_add(source.rendered_command_count);
1796    aggregate.dropped_command_count = aggregate
1797        .dropped_command_count
1798        .saturating_add(source.dropped_command_count);
1799    aggregate.command_counts = aggregate.command_counts.adding(source.command_counts);
1800    aggregate.rendered_counts = aggregate.rendered_counts.adding(source.rendered_counts);
1801    aggregate.dropped_counts = aggregate.dropped_counts.adding(source.dropped_counts);
1802    aggregate.vertex_count = aggregate.vertex_count.saturating_add(source.vertex_count);
1803    aggregate.draw_batch_count = aggregate
1804        .draw_batch_count
1805        .saturating_add(source.draw_batch_count);
1806    aggregate.upload_bytes = aggregate.upload_bytes.saturating_add(source.upload_bytes);
1807}
1808
1809#[allow(clippy::too_many_arguments)]
1810fn frame_report(
1811    status: RenderStatus,
1812    statistics: FrameStatistics,
1813    tessellation: Duration,
1814    upload: Duration,
1815    camera_uniform_upload: Duration,
1816    surface_acquire: Duration,
1817    encode_submit_present: Duration,
1818    total_cpu: Duration,
1819    geometry_reused: bool,
1820    geometry_streamed: bool,
1821    tessellation_stats: TessellationStats,
1822) -> FrameReport {
1823    let report = render_report(
1824        status,
1825        tessellation,
1826        upload,
1827        camera_uniform_upload,
1828        surface_acquire,
1829        encode_submit_present,
1830        total_cpu,
1831        geometry_reused,
1832        geometry_streamed,
1833        tessellation_stats,
1834    );
1835    FrameReport {
1836        status: report.status,
1837        statistics,
1838        metrics: report.metrics,
1839        gpu_timing_id: None,
1840    }
1841}