Skip to main content

sim_engine/renderer/
particles.rs

1//! Retained particle-field updates, bounded visibility and draw submission.
2
3use super::{
4    Arc, Camera2d, CameraUniform, Color, Duration, Error, Instant, LogicalViewport,
5    ParticleDrawPreparation, ParticleGpu, ParticleInstance2d, RenderReport, RenderStatus,
6    RenderTarget2d, RenderTargetLoad, RendererFrameError, RendererSurfaceStatus, TessellationStats,
7    WgpuRenderer, allocate_particle_staging, buffer_capacity_fits, compact_particle_instances,
8    create_particle_instance_buffer, fmt, particle_budgeted_capacity, particle_idle_statistics,
9    particle_instances_to_gpu, particle_statistics_with_budget, particle_update_range,
10    particle_visible_index_is_selected, premultiplied_wgpu_color, prepared_scene_belongs_to,
11    render_report, restore_particle_field_resources, uniformly_sampled_index,
12    validate_particle_retained_capacities, validate_particle_retained_count,
13    validate_particle_staging_capacity, visible_particle_count,
14};
15
16/// Counts associated with one particle-field update or draw.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub struct ParticleStatistics {
19    pub(super) submitted: usize,
20    pub(super) visibility_checked: usize,
21    pub(super) visible: usize,
22    pub(super) culled: usize,
23    pub(super) budget_limited: usize,
24    pub(super) dropped: usize,
25    pub(super) rendered: usize,
26}
27
28impl ParticleStatistics {
29    /// Returns instances supplied by the host.
30    pub fn submitted(self) -> usize {
31        self.submitted
32    }
33
34    /// Returns instances tested against the camera viewport this frame.
35    pub fn visibility_checked(self) -> usize {
36        self.visibility_checked
37    }
38
39    /// Returns checked instances that intersect the camera viewport.
40    pub fn visible(self) -> usize {
41        self.visible
42    }
43
44    /// Returns instances outside the current camera viewport.
45    pub fn culled(self) -> usize {
46        self.culled
47    }
48
49    /// Returns unchecked or camera-visible instances omitted by the render budget.
50    pub fn budget_limited(self) -> usize {
51        self.budget_limited
52    }
53
54    /// Returns instances rejected before GPU submission.
55    pub fn dropped(self) -> usize {
56        self.dropped
57    }
58
59    /// Returns instances submitted to the particle draw call.
60    pub fn rendered(self) -> usize {
61        self.rendered
62    }
63}
64
65/// Hard steady-state per-field limits for bounding particle visualization.
66///
67/// Atomic replacement temporarily retains the old and fully prepared new
68/// state together. Its CPU/GPU peak is therefore bounded by the sum of the old
69/// and new budgets, while every committed field stays within its own budget.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct ParticleRenderBudget {
72    pub(super) max_visible_instances: usize,
73    pub(super) max_retained_bytes: usize,
74    pub(super) max_gpu_bytes: usize,
75    pub(super) max_upload_bytes_per_frame: usize,
76    pub(super) max_visibility_checks_per_frame: usize,
77}
78
79impl ParticleRenderBudget {
80    /// Bytes used by one retained or visibility-staging particle slot.
81    pub const INSTANCE_BYTES: usize = std::mem::size_of::<ParticleGpu>();
82
83    /// No application-level cap beyond active-device allocation limits.
84    pub const UNBOUNDED: Self = Self {
85        max_visible_instances: usize::MAX,
86        max_retained_bytes: usize::MAX,
87        max_gpu_bytes: usize::MAX,
88        max_upload_bytes_per_frame: usize::MAX,
89        max_visibility_checks_per_frame: usize::MAX,
90    };
91
92    /// Creates explicit visible-instance, retained-CPU, GPU-memory, and
93    /// per-frame upload caps.
94    pub fn new(
95        max_visible_instances: usize,
96        max_retained_bytes: usize,
97        max_gpu_bytes: usize,
98        max_upload_bytes_per_frame: usize,
99    ) -> Result<Self, ParticleBudgetError> {
100        let minimum_bytes = Self::INSTANCE_BYTES;
101        let minimum_retained_bytes = minimum_bytes.saturating_mul(2);
102        if max_visible_instances == 0
103            || max_visible_instances > u32::MAX as usize
104            || max_retained_bytes < minimum_retained_bytes
105            || max_gpu_bytes < minimum_bytes
106            || max_upload_bytes_per_frame < minimum_bytes
107        {
108            return Err(ParticleBudgetError::InvalidLimit);
109        }
110        Ok(Self {
111            max_visible_instances,
112            max_retained_bytes,
113            max_gpu_bytes,
114            max_upload_bytes_per_frame,
115            max_visibility_checks_per_frame: usize::MAX,
116        })
117    }
118
119    /// Caps camera visibility checks while sampling candidates uniformly across
120    /// the retained field. The cap must fit the effective visible-instance cap.
121    pub fn with_max_visibility_checks(
122        mut self,
123        max_visibility_checks_per_frame: usize,
124    ) -> Result<Self, ParticleBudgetError> {
125        if max_visibility_checks_per_frame < self.instance_limit() {
126            return Err(ParticleBudgetError::InvalidLimit);
127        }
128        self.max_visibility_checks_per_frame = max_visibility_checks_per_frame;
129        Ok(self)
130    }
131
132    /// Returns the maximum camera-visible instances considered for drawing.
133    pub const fn max_visible_instances(self) -> usize {
134        self.max_visible_instances
135    }
136
137    /// Returns the maximum steady-state engine-owned particle allocation in bytes.
138    pub const fn max_retained_bytes(self) -> usize {
139        self.max_retained_bytes
140    }
141
142    /// Returns the maximum particle instance-buffer allocation in bytes.
143    pub const fn max_gpu_bytes(self) -> usize {
144        self.max_gpu_bytes
145    }
146
147    /// Returns the maximum particle bytes uploaded by one render call.
148    pub const fn max_upload_bytes_per_frame(self) -> usize {
149        self.max_upload_bytes_per_frame
150    }
151
152    /// Returns the maximum retained instances checked against the viewport.
153    pub const fn max_visibility_checks_per_frame(self) -> usize {
154        self.max_visibility_checks_per_frame
155    }
156
157    pub(super) fn instance_limit(self) -> usize {
158        self.max_visible_instances
159            .min(self.max_gpu_bytes / std::mem::size_of::<ParticleGpu>())
160            .min(self.max_upload_bytes_per_frame / std::mem::size_of::<ParticleGpu>())
161    }
162}
163
164impl Default for ParticleRenderBudget {
165    fn default() -> Self {
166        Self::UNBOUNDED
167    }
168}
169
170/// Invalid particle visualization resource budget.
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub enum ParticleBudgetError {
173    /// CPU retention must fit one source plus one staging slot; GPU/upload
174    /// limits must each fit at least one visible particle instance.
175    InvalidLimit,
176}
177
178impl fmt::Display for ParticleBudgetError {
179    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
180        write!(
181            formatter,
182            "particle budget must fit one retained instance, its visibility staging slot, and one visible GPU upload"
183        )
184    }
185}
186
187impl Error for ParticleBudgetError {}
188
189/// Renderer-owned instanced particles for high-volume simulation visuals.
190///
191/// The field retains its validated CPU instances so it can be recreated after
192/// device loss. Its GPU instance buffer grows only when a replacement exceeds
193/// the current capacity.
194pub struct ParticleField2d {
195    pub(super) renderer_identity: Arc<()>,
196    pub(super) instance_buffer: Arc<wgpu::Buffer>,
197    pub(super) instances: Vec<ParticleGpu>,
198    pub(super) visible_instances: Vec<ParticleGpu>,
199    pub(super) instance_capacity: usize,
200    pub(super) budget: ParticleRenderBudget,
201    pub(super) statistics: ParticleStatistics,
202}
203
204impl ParticleField2d {
205    /// Returns the number of particle instances currently stored.
206    pub fn instance_count(&self) -> usize {
207        self.instances.len()
208    }
209
210    /// Returns the number of instances that fit without reallocating GPU memory.
211    pub fn instance_capacity(&self) -> usize {
212        self.instance_capacity
213    }
214
215    /// Returns the most recent update or draw counts.
216    pub fn statistics(&self) -> ParticleStatistics {
217        self.statistics
218    }
219
220    /// Returns the hard visualization budget applied by rendering.
221    pub fn budget(&self) -> ParticleRenderBudget {
222        self.budget
223    }
224
225    /// Returns retained CPU memory used for recovery and validation.
226    pub fn recovery_memory_bytes(&self) -> usize {
227        self.instances
228            .capacity()
229            .saturating_mul(std::mem::size_of::<ParticleGpu>())
230    }
231
232    /// Returns currently reserved CPU bytes for retained and culled instance lists.
233    pub fn cpu_allocation_bytes(&self) -> usize {
234        self.instances
235            .capacity()
236            .saturating_add(self.visible_instances.capacity())
237            .saturating_mul(std::mem::size_of::<ParticleGpu>())
238    }
239
240    /// Returns allocated GPU instance-buffer bytes.
241    pub fn gpu_allocation_bytes(&self) -> usize {
242        self.instance_capacity
243            .saturating_mul(std::mem::size_of::<ParticleGpu>())
244    }
245}
246
247/// Failure while creating or updating a [`ParticleField2d`].
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub enum ParticleFieldError {
250    /// An input instance violates the portable particle contract.
251    InvalidInstance,
252    /// A partial update lies outside the field's current instance range.
253    UpdateRangeOutOfBounds,
254    /// The field belongs to another renderer and GPU device.
255    RendererMismatch,
256    /// The instance capacity exceeds the current device's buffer limit.
257    CapacityTooLarge,
258    /// The retained CPU allocation exceeds the host-selected hard ceiling.
259    RetainedBudgetExceeded {
260        /// Configured retained-allocation ceiling.
261        limit: usize,
262        /// Required or actually reserved retained bytes.
263        actual: usize,
264    },
265    /// Particle retention, replacement, or visibility-staging storage could
266    /// not be reserved without panicking.
267    AllocationFailed {
268        /// Bytes requested by the failed particle-storage reservation.
269        requested_bytes: usize,
270    },
271}
272
273impl fmt::Display for ParticleFieldError {
274    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
275        match self {
276            Self::InvalidInstance => write!(
277                formatter,
278                "particle field positions, depth, and radius must be portable and colors valid"
279            ),
280            Self::UpdateRangeOutOfBounds => {
281                write!(
282                    formatter,
283                    "particle update range is outside the current field"
284                )
285            }
286            Self::RendererMismatch => {
287                write!(formatter, "particle field belongs to a different renderer")
288            }
289            Self::CapacityTooLarge => {
290                write!(
291                    formatter,
292                    "particle field exceeds the GPU instance-buffer limit"
293                )
294            }
295            Self::RetainedBudgetExceeded { limit, actual } => write!(
296                formatter,
297                "particle retained CPU allocation {actual} bytes exceeds limit {limit}"
298            ),
299            Self::AllocationFailed { requested_bytes } => write!(
300                formatter,
301                "could not reserve {requested_bytes} bytes for particle storage"
302            ),
303        }
304    }
305}
306
307impl Error for ParticleFieldError {}
308
309/// CPU-side outcome of one particle-field update.
310#[derive(Debug, Clone, Copy, PartialEq, Eq)]
311pub struct ParticleFieldUpdateReport {
312    statistics: ParticleStatistics,
313    preparation: Duration,
314    reallocated: bool,
315}
316
317impl ParticleFieldUpdateReport {
318    /// Returns submitted, visible, dropped, and rendered instance counts.
319    pub fn statistics(self) -> ParticleStatistics {
320        self.statistics
321    }
322
323    /// Returns CPU time spent validating and retaining the new visual state.
324    ///
325    /// GPU upload is deferred until rendering, after camera culling has selected
326    /// the compact visible set.
327    pub fn preparation(self) -> Duration {
328        self.preparation
329    }
330
331    /// Backward-compatible alias for [`ParticleFieldUpdateReport::preparation`].
332    #[deprecated(note = "particle GPU upload is deferred to render; use preparation()")]
333    pub fn upload(self) -> Duration {
334        self.preparation
335    }
336
337    /// Returns whether this update grew and replaced the GPU instance buffer.
338    pub fn reallocated(self) -> bool {
339        self.reallocated
340    }
341}
342
343/// Failure while rendering a [`ParticleField2d`].
344#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub enum ParticleFieldRenderError {
346    /// The field belongs to another renderer and GPU device.
347    RendererMismatch,
348    /// The clear color is not normalized linear RGBA.
349    InvalidBackground,
350    /// Particle projection cannot be proven inside the portable GPU envelope.
351    InvalidGeometryTransform,
352    /// Surface acquisition or presentation failed.
353    Frame(RendererFrameError),
354}
355
356impl fmt::Display for ParticleFieldRenderError {
357    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
358        match self {
359            Self::RendererMismatch => {
360                write!(formatter, "particle field belongs to a different renderer")
361            }
362            Self::InvalidBackground => {
363                write!(formatter, "particle field background must be normalized")
364            }
365            Self::InvalidGeometryTransform => {
366                write!(formatter, "particle field geometry transform is invalid")
367            }
368            Self::Frame(error) => write!(formatter, "particle field frame failed: {error}"),
369        }
370    }
371}
372
373impl Error for ParticleFieldRenderError {}
374
375impl WgpuRenderer {
376    /// Creates an instanced particle field owned by this renderer.
377    ///
378    /// Each instance draws as one screen-space circle quad through a single GPU
379    /// draw call. The retained CPU snapshot enables later restoration on a
380    /// recreated renderer.
381    pub fn create_particle_field(
382        &self,
383        instances: &[ParticleInstance2d],
384    ) -> Result<ParticleField2d, ParticleFieldError> {
385        self.create_particle_field_with_budget(instances, ParticleRenderBudget::UNBOUNDED)
386    }
387
388    /// Creates an instanced particle field with hard retained-CPU, GPU-memory,
389    /// upload, visible-instance, and visibility-work limits.
390    pub fn create_particle_field_with_budget(
391        &self,
392        instances: &[ParticleInstance2d],
393        budget: ParticleRenderBudget,
394    ) -> Result<ParticleField2d, ParticleFieldError> {
395        validate_particle_retained_count(instances.len(), budget)?;
396        let instance_capacity = particle_budgeted_capacity(instances.len(), budget)
397            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
398            .ok_or(ParticleFieldError::CapacityTooLarge)?;
399        let instances = particle_instances_to_gpu(instances)?;
400        let visible_instances = allocate_particle_staging(instances.len(), budget)?;
401        validate_particle_retained_capacities(
402            instances.capacity(),
403            visible_instances.capacity(),
404            budget,
405        )?;
406        let instance_buffer = Arc::new(create_particle_instance_buffer(
407            &self.device,
408            instance_capacity,
409        ));
410        Ok(ParticleField2d {
411            renderer_identity: Arc::clone(&self.renderer_identity),
412            instance_buffer,
413            statistics: particle_idle_statistics(instances.len()),
414            instances,
415            visible_instances,
416            instance_capacity,
417            budget,
418        })
419    }
420
421    /// Replaces a particle field's hard resource budget, shrinking memory when required.
422    pub fn set_particle_field_budget(
423        &self,
424        field: &mut ParticleField2d,
425        budget: ParticleRenderBudget,
426    ) -> Result<(), ParticleFieldError> {
427        self.validate_particle_field(field)?;
428        validate_particle_retained_count(field.instances.len(), budget)?;
429        let desired_capacity = particle_budgeted_capacity(field.instances.len(), budget)
430            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
431            .ok_or(ParticleFieldError::CapacityTooLarge)?;
432        let visible_instances = allocate_particle_staging(field.instances.len(), budget)?;
433        let replacement_instances = compact_particle_instances(
434            &field.instances,
435            field.instances.capacity(),
436            visible_instances.capacity(),
437            budget,
438        )?;
439        let replacement_buffer = (desired_capacity != field.instance_capacity).then(|| {
440            Arc::new(create_particle_instance_buffer(
441                &self.device,
442                desired_capacity,
443            ))
444        });
445        if let Some(instance_buffer) = replacement_buffer {
446            field.instance_buffer = instance_buffer;
447            field.instance_capacity = desired_capacity;
448        }
449        if let Some(instances) = replacement_instances {
450            field.instances = instances;
451        }
452        field.budget = budget;
453        field.visible_instances = visible_instances;
454        field.statistics = particle_idle_statistics(field.instances.len());
455        Ok(())
456    }
457
458    /// Replaces all particle instances, reusing GPU capacity whenever possible.
459    pub fn update_particle_field(
460        &self,
461        field: &mut ParticleField2d,
462        instances: &[ParticleInstance2d],
463    ) -> Result<ParticleStatistics, ParticleFieldError> {
464        self.update_particle_field_with_metrics(field, instances)
465            .map(|report| report.statistics())
466    }
467
468    /// Replaces all particle instances and returns CPU-side preparation metrics.
469    pub fn update_particle_field_with_metrics(
470        &self,
471        field: &mut ParticleField2d,
472        instances: &[ParticleInstance2d],
473    ) -> Result<ParticleFieldUpdateReport, ParticleFieldError> {
474        let update_started_at = Instant::now();
475        self.validate_particle_field(field)?;
476        validate_particle_retained_count(instances.len(), field.budget)?;
477        let desired_capacity = particle_budgeted_capacity(instances.len(), field.budget)
478            .filter(|capacity| buffer_capacity_fits::<ParticleGpu>(&self.device, *capacity))
479            .ok_or(ParticleFieldError::CapacityTooLarge)?;
480        let instances = particle_instances_to_gpu(instances)?;
481        let visible_instances = allocate_particle_staging(instances.len(), field.budget)?;
482        validate_particle_retained_capacities(
483            instances.capacity(),
484            visible_instances.capacity(),
485            field.budget,
486        )?;
487        let reallocated = desired_capacity > field.instance_capacity;
488        let replacement_buffer = reallocated.then(|| {
489            Arc::new(create_particle_instance_buffer(
490                &self.device,
491                desired_capacity,
492            ))
493        });
494        if let Some(instance_buffer) = replacement_buffer {
495            field.instance_buffer = instance_buffer;
496            field.instance_capacity = desired_capacity;
497        }
498        field.statistics = particle_idle_statistics(instances.len());
499        field.instances = instances;
500        field.visible_instances = visible_instances;
501        Ok(ParticleFieldUpdateReport {
502            statistics: field.statistics,
503            preparation: update_started_at.elapsed(),
504            reallocated,
505        })
506    }
507
508    /// Replaces a contiguous particle range without reallocating its GPU buffer.
509    pub fn update_particle_field_range(
510        &self,
511        field: &mut ParticleField2d,
512        first_instance: usize,
513        instances: &[ParticleInstance2d],
514    ) -> Result<ParticleStatistics, ParticleFieldError> {
515        self.update_particle_field_range_with_metrics(field, first_instance, instances)
516            .map(|report| report.statistics())
517    }
518
519    /// Replaces a particle range and returns CPU-side preparation metrics.
520    pub fn update_particle_field_range_with_metrics(
521        &self,
522        field: &mut ParticleField2d,
523        first_instance: usize,
524        instances: &[ParticleInstance2d],
525    ) -> Result<ParticleFieldUpdateReport, ParticleFieldError> {
526        let update_started_at = Instant::now();
527        self.validate_particle_field(field)?;
528        let range = particle_update_range(first_instance, instances.len(), field.instances.len())?;
529        let instances = particle_instances_to_gpu(instances)?;
530        if !instances.is_empty() {
531            field.instances[range].copy_from_slice(&instances);
532        }
533        field.statistics = particle_idle_statistics(field.instances.len());
534        Ok(ParticleFieldUpdateReport {
535            statistics: field.statistics,
536            preparation: update_started_at.elapsed(),
537            reallocated: false,
538        })
539    }
540
541    /// Recreates a particle field on this renderer from retained CPU instances.
542    pub fn restore_particle_field(
543        &self,
544        source: &ParticleField2d,
545    ) -> Result<ParticleField2d, ParticleFieldError> {
546        restore_particle_field_resources(
547            &self.device,
548            &self.queue,
549            Arc::clone(&self.renderer_identity),
550            source,
551        )
552    }
553
554    /// Draws a particle field with a normalized clear color.
555    pub fn render_particle_field(
556        &mut self,
557        field: &mut ParticleField2d,
558        background: Color,
559        camera: &Camera2d,
560    ) -> Result<RenderStatus, ParticleFieldRenderError> {
561        self.render_particle_field_with_metrics(field, background, camera)
562            .map(RenderReport::status)
563    }
564
565    /// Draws a particle field and returns regular per-frame renderer metrics.
566    pub fn render_particle_field_with_metrics(
567        &mut self,
568        field: &mut ParticleField2d,
569        background: Color,
570        camera: &Camera2d,
571    ) -> Result<RenderReport, ParticleFieldRenderError> {
572        self.validate_particle_field(field)
573            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
574        if !background.is_normalized() {
575            return Err(ParticleFieldRenderError::InvalidBackground);
576        }
577        self.draw_particle_field(background, field, *camera, Instant::now())
578            .map_err(|error| match error {
579                RendererFrameError::InvalidGeometryTransform => {
580                    ParticleFieldRenderError::InvalidGeometryTransform
581                }
582                other => ParticleFieldRenderError::Frame(other),
583            })
584    }
585
586    /// Draws a particle field into an offscreen target.
587    ///
588    /// Target dimensions may be lower than the presentation surface to bound
589    /// raster cost. Camera coordinates and particle radii remain expressed in
590    /// logical presentation pixels, so composing the target back to the surface
591    /// preserves layout while trading only raster resolution.
592    pub fn render_particle_field_to_target(
593        &mut self,
594        target: &RenderTarget2d,
595        field: &mut ParticleField2d,
596        camera: &Camera2d,
597        load: RenderTargetLoad,
598    ) -> Result<RenderReport, ParticleFieldRenderError> {
599        self.validate_render_target(target)
600            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
601        self.validate_particle_field(field)
602            .map_err(|_| ParticleFieldRenderError::RendererMismatch)?;
603        if matches!(load, RenderTargetLoad::Clear(color) if !color.is_normalized()) {
604            return Err(ParticleFieldRenderError::InvalidBackground);
605        }
606        self.draw_particle_field_to_target(target, field, *camera, load, Instant::now())
607            .map_err(|error| match error {
608                RendererFrameError::InvalidGeometryTransform => {
609                    ParticleFieldRenderError::InvalidGeometryTransform
610                }
611                other => ParticleFieldRenderError::Frame(other),
612            })
613    }
614
615    pub(super) fn prepare_particle_draw(
616        &self,
617        field: &mut ParticleField2d,
618        camera: Camera2d,
619    ) -> Result<ParticleDrawPreparation, RendererFrameError> {
620        let (logical_width, logical_height) = self.logical_size();
621        let viewport = LogicalViewport::new(logical_width, logical_height)
622            .map_err(|_| RendererFrameError::InvalidGeometryTransform)?;
623        let Some(camera_uniform) = CameraUniform::new(camera, viewport) else {
624            return Err(RendererFrameError::InvalidGeometryTransform);
625        };
626        let instance_count = field.instances.len();
627        let visibility_checked = instance_count.min(field.budget.max_visibility_checks_per_frame);
628        if visibility_checked < instance_count {
629            field.visible_instances.clear();
630            validate_particle_staging_capacity(&field.visible_instances, visibility_checked)?;
631            for candidate_index in 0..visibility_checked {
632                let source_index =
633                    uniformly_sampled_index(candidate_index, instance_count, visibility_checked);
634                let instance = field.instances[source_index];
635                let Some(intersects) =
636                    instance.validated_viewport_intersection(camera_uniform, viewport)
637                else {
638                    return Err(RendererFrameError::InvalidGeometryTransform);
639                };
640                if intersects {
641                    field.visible_instances.push(instance);
642                }
643            }
644            let visible_count = field.visible_instances.len();
645            let selected_count = visible_count.min(field.budget.instance_limit());
646            if selected_count < visible_count {
647                let mut visible_index = 0;
648                field.visible_instances.retain(|_| {
649                    let selected = particle_visible_index_is_selected(
650                        visible_index,
651                        visible_count,
652                        selected_count,
653                    );
654                    visible_index += 1;
655                    selected
656                });
657            }
658            let statistics = particle_statistics_with_budget(
659                instance_count,
660                visibility_checked,
661                visible_count,
662                selected_count,
663                0,
664            );
665            return Ok(ParticleDrawPreparation {
666                camera_uniform,
667                visible_count: selected_count,
668                statistics,
669            });
670        }
671
672        let visible_count = visible_particle_count(&field.instances, camera_uniform, viewport)?;
673        let selected_count = visible_count.min(field.budget.instance_limit());
674        let statistics = particle_statistics_with_budget(
675            instance_count,
676            instance_count,
677            visible_count,
678            selected_count,
679            0,
680        );
681        if selected_count == field.instances.len() {
682            field.visible_instances.clear();
683        } else {
684            field.visible_instances.clear();
685            validate_particle_staging_capacity(&field.visible_instances, selected_count)?;
686            let mut visible_index = 0;
687            for instance in field.instances.iter().copied() {
688                if !instance.intersects_viewport(camera_uniform, viewport) {
689                    continue;
690                }
691                let selected_index = field.visible_instances.len();
692                if selected_index < selected_count
693                    && particle_visible_index_is_selected(
694                        visible_index,
695                        visible_count,
696                        selected_count,
697                    )
698                {
699                    field.visible_instances.push(instance);
700                }
701                visible_index += 1;
702            }
703        }
704        Ok(ParticleDrawPreparation {
705            camera_uniform,
706            visible_count: selected_count,
707            statistics,
708        })
709    }
710
711    pub(super) fn upload_particle_draw(
712        &self,
713        field: &ParticleField2d,
714        preparation: ParticleDrawPreparation,
715    ) -> (Duration, Duration) {
716        let visible_instances = if field.visible_instances.is_empty()
717            && preparation.visible_count == field.instances.len()
718        {
719            field.instances.as_slice()
720        } else {
721            field.visible_instances.as_slice()
722        };
723        let upload_started_at = Instant::now();
724        if !visible_instances.is_empty() {
725            self.queue.write_buffer(
726                &field.instance_buffer,
727                0,
728                bytemuck::cast_slice(visible_instances),
729            );
730        }
731        let upload = upload_started_at.elapsed();
732        let camera_uniform_upload_started_at = Instant::now();
733        self.queue.write_buffer(
734            &self.camera_uniform_buffer,
735            0,
736            bytemuck::bytes_of(&preparation.camera_uniform),
737        );
738        let camera_uniform_upload = camera_uniform_upload_started_at.elapsed();
739        (upload, camera_uniform_upload)
740    }
741
742    fn draw_particle_field(
743        &mut self,
744        background: Color,
745        field: &mut ParticleField2d,
746        camera: Camera2d,
747        frame_started_at: Instant,
748    ) -> Result<RenderReport, RendererFrameError> {
749        let preparation_started_at = Instant::now();
750        let preparation = self.prepare_particle_draw(field, camera)?;
751        let preparation_duration = preparation_started_at.elapsed();
752
753        let surface_acquire_started_at = Instant::now();
754        let surface_texture = match self.surface.get_current_texture() {
755            wgpu::CurrentSurfaceTexture::Success(texture)
756            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
757            wgpu::CurrentSurfaceTexture::Timeout => {
758                field.statistics = preparation.statistics;
759                return Ok(render_report(
760                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
761                    preparation_duration,
762                    Duration::ZERO,
763                    Duration::ZERO,
764                    surface_acquire_started_at.elapsed(),
765                    Duration::ZERO,
766                    frame_started_at.elapsed(),
767                    false,
768                    true,
769                    TessellationStats::default(),
770                ));
771            }
772            wgpu::CurrentSurfaceTexture::Occluded => {
773                field.statistics = preparation.statistics;
774                return Ok(render_report(
775                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
776                    preparation_duration,
777                    Duration::ZERO,
778                    Duration::ZERO,
779                    surface_acquire_started_at.elapsed(),
780                    Duration::ZERO,
781                    frame_started_at.elapsed(),
782                    false,
783                    true,
784                    TessellationStats::default(),
785                ));
786            }
787            wgpu::CurrentSurfaceTexture::Outdated => {
788                let _ = self.resize(self.config.width, self.config.height);
789                field.statistics = preparation.statistics;
790                return Ok(render_report(
791                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
792                    preparation_duration,
793                    Duration::ZERO,
794                    Duration::ZERO,
795                    surface_acquire_started_at.elapsed(),
796                    Duration::ZERO,
797                    frame_started_at.elapsed(),
798                    false,
799                    true,
800                    TessellationStats::default(),
801                ));
802            }
803            wgpu::CurrentSurfaceTexture::Lost => {
804                return Err(RendererFrameError::Surface(RendererSurfaceStatus::Lost));
805            }
806            wgpu::CurrentSurfaceTexture::Validation => {
807                return Err(RendererFrameError::Surface(
808                    RendererSurfaceStatus::Validation,
809                ));
810            }
811        };
812        let surface_acquire = surface_acquire_started_at.elapsed();
813        let (upload, camera_uniform_upload) = self.upload_particle_draw(field, preparation);
814        let encode_submit_present_started_at = Instant::now();
815        let surface_view = surface_texture
816            .texture
817            .create_view(&wgpu::TextureViewDescriptor::default());
818        let (view, resolve_target) = match &self.multisample_target {
819            Some(target) => (&target.view, Some(&surface_view)),
820            None => (&surface_view, None),
821        };
822        let mut encoder = self
823            .device
824            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
825                label: Some("sim-engine particle render encoder"),
826            });
827        {
828            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
829                label: Some("sim-engine particle render pass"),
830                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
831                    view,
832                    depth_slice: None,
833                    resolve_target,
834                    ops: wgpu::Operations {
835                        load: wgpu::LoadOp::Clear(background.to_wgpu()),
836                        store: wgpu::StoreOp::Store,
837                    },
838                })],
839                depth_stencil_attachment: None,
840                timestamp_writes: None,
841                occlusion_query_set: None,
842                multiview_mask: None,
843            });
844            if preparation.visible_count > 0 {
845                pass.set_pipeline(&self.particle_pipeline);
846                pass.set_bind_group(0, &self.camera_bind_group, &[]);
847                pass.set_vertex_buffer(0, self.particle_unit_buffer.slice(..));
848                pass.set_vertex_buffer(1, field.instance_buffer.slice(..));
849                pass.draw(0..6, 0..preparation.visible_count as u32);
850            }
851        }
852        self.queue.submit([encoder.finish()]);
853        self.notify_before_present();
854        self.queue.present(surface_texture);
855        field.statistics = ParticleStatistics {
856            rendered: preparation.visible_count,
857            ..preparation.statistics
858        };
859        Ok(render_report(
860            RenderStatus::Drawn,
861            preparation_duration,
862            upload,
863            camera_uniform_upload,
864            surface_acquire,
865            encode_submit_present_started_at.elapsed(),
866            frame_started_at.elapsed(),
867            false,
868            true,
869            TessellationStats::default(),
870        ))
871    }
872
873    fn draw_particle_field_to_target(
874        &self,
875        target: &RenderTarget2d,
876        field: &mut ParticleField2d,
877        camera: Camera2d,
878        load: RenderTargetLoad,
879        frame_started_at: Instant,
880    ) -> Result<RenderReport, RendererFrameError> {
881        let preparation_started_at = Instant::now();
882        let preparation = self.prepare_particle_draw(field, camera)?;
883        let preparation_duration = preparation_started_at.elapsed();
884        let (upload, camera_uniform_upload) = self.upload_particle_draw(field, preparation);
885        let encode_started_at = Instant::now();
886        let mut encoder = self
887            .device
888            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
889                label: Some("sim-engine target particle encoder"),
890            });
891        {
892            let load = match load {
893                RenderTargetLoad::Load => wgpu::LoadOp::Load,
894                RenderTargetLoad::Clear(color) => {
895                    wgpu::LoadOp::Clear(premultiplied_wgpu_color(color))
896                }
897            };
898            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
899                label: Some("sim-engine target particle pass"),
900                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
901                    view: &target.view,
902                    depth_slice: None,
903                    resolve_target: None,
904                    ops: wgpu::Operations {
905                        load,
906                        store: wgpu::StoreOp::Store,
907                    },
908                })],
909                depth_stencil_attachment: None,
910                timestamp_writes: None,
911                occlusion_query_set: None,
912                multiview_mask: None,
913            });
914            if preparation.visible_count > 0 {
915                pass.set_pipeline(&self.target_particle_pipeline);
916                pass.set_bind_group(0, &self.camera_bind_group, &[]);
917                pass.set_vertex_buffer(0, self.particle_unit_buffer.slice(..));
918                pass.set_vertex_buffer(1, field.instance_buffer.slice(..));
919                pass.draw(0..6, 0..preparation.visible_count as u32);
920            }
921        }
922        self.queue.submit([encoder.finish()]);
923        field.statistics = ParticleStatistics {
924            rendered: preparation.visible_count,
925            ..preparation.statistics
926        };
927        Ok(render_report(
928            RenderStatus::Drawn,
929            preparation_duration,
930            upload,
931            camera_uniform_upload,
932            Duration::ZERO,
933            encode_started_at.elapsed(),
934            frame_started_at.elapsed(),
935            false,
936            true,
937            TessellationStats::default(),
938        ))
939    }
940
941    pub(super) fn validate_particle_field(
942        &self,
943        field: &ParticleField2d,
944    ) -> Result<(), ParticleFieldError> {
945        prepared_scene_belongs_to(&self.renderer_identity, &field.renderer_identity)
946            .then_some(())
947            .ok_or(ParticleFieldError::RendererMismatch)
948    }
949}