Skip to main content

sim_engine/renderer/
visualization.rs

1use super::*;
2
3pub(super) struct CompositionPipelines {
4    pub(super) alpha: wgpu::RenderPipeline,
5    pub(super) additive: wgpu::RenderPipeline,
6    pub(super) replace: wgpu::RenderPipeline,
7    pub(super) uniform_buffer: wgpu::Buffer,
8    pub(super) secondary_uniform_buffer: wgpu::Buffer,
9    pub(super) bind_group_layout: wgpu::BindGroupLayout,
10}
11
12pub(super) struct CachedColorMap {
13    pub(super) lut: [u8; COLOR_MAP_LUT_SIZE as usize * 4],
14    pub(super) _texture: wgpu::Texture,
15    pub(super) view: wgpu::TextureView,
16}
17
18impl CompositionPipelines {
19    pub(super) fn pipeline(&self, blend_mode: BlendMode) -> &wgpu::RenderPipeline {
20        match blend_mode {
21            BlendMode::Alpha => &self.alpha,
22            BlendMode::Additive => &self.additive,
23            BlendMode::Replace => &self.replace,
24        }
25    }
26}
27
28pub(super) fn create_composition_pipeline(
29    device: &wgpu::Device,
30    shader: &wgpu::ShaderModule,
31    layout: &wgpu::PipelineLayout,
32    format: wgpu::TextureFormat,
33    sample_count: u32,
34    blend_mode: BlendMode,
35) -> wgpu::RenderPipeline {
36    let blend = match blend_mode {
37        BlendMode::Alpha => Some(wgpu::BlendState::ALPHA_BLENDING),
38        BlendMode::Additive => Some(wgpu::BlendState {
39            color: wgpu::BlendComponent {
40                src_factor: wgpu::BlendFactor::SrcAlpha,
41                dst_factor: wgpu::BlendFactor::One,
42                operation: wgpu::BlendOperation::Add,
43            },
44            alpha: wgpu::BlendComponent {
45                src_factor: wgpu::BlendFactor::One,
46                dst_factor: wgpu::BlendFactor::One,
47                operation: wgpu::BlendOperation::Add,
48            },
49        }),
50        BlendMode::Replace => Some(wgpu::BlendState {
51            // `composite_fs_main` produces straight RGB. Preserve the target
52            // representation by premultiplying on write while replacing every
53            // destination component.
54            color: wgpu::BlendComponent {
55                src_factor: wgpu::BlendFactor::SrcAlpha,
56                dst_factor: wgpu::BlendFactor::Zero,
57                operation: wgpu::BlendOperation::Add,
58            },
59            alpha: wgpu::BlendComponent {
60                src_factor: wgpu::BlendFactor::One,
61                dst_factor: wgpu::BlendFactor::Zero,
62                operation: wgpu::BlendOperation::Add,
63            },
64        }),
65    };
66    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
67        label: Some("sim-engine composition pipeline"),
68        layout: Some(layout),
69        vertex: wgpu::VertexState {
70            module: shader,
71            entry_point: Some("composite_vs_main"),
72            compilation_options: wgpu::PipelineCompilationOptions::default(),
73            buffers: &[],
74        },
75        primitive: wgpu::PrimitiveState {
76            topology: wgpu::PrimitiveTopology::TriangleList,
77            ..Default::default()
78        },
79        depth_stencil: None,
80        multisample: wgpu::MultisampleState {
81            count: sample_count,
82            ..Default::default()
83        },
84        fragment: Some(wgpu::FragmentState {
85            module: shader,
86            entry_point: Some("composite_fs_main"),
87            compilation_options: wgpu::PipelineCompilationOptions::default(),
88            targets: &[Some(wgpu::ColorTargetState {
89                format,
90                blend,
91                write_mask: wgpu::ColorWrites::ALL,
92            })],
93        }),
94        multiview_mask: None,
95        cache: None,
96    })
97}
98
99/// Validated presentation settings for a scalar field with a particle overlay.
100///
101/// This is a rendering composition contract, not a simulation data model. The
102/// host remains responsible for producing both the scalar and particle state.
103#[derive(Debug, Clone, Copy, PartialEq)]
104pub struct LayeredVisualizationOptions {
105    minimum: f32,
106    maximum: f32,
107    value_extent: f32,
108    sampling: ScalarFieldSampling,
109    blend_mode: BlendMode,
110    opacity: f32,
111    target_background: Color,
112    surface_background: Color,
113}
114
115impl LayeredVisualizationOptions {
116    /// Creates settings with linear field sampling and opaque replacement.
117    pub fn new(
118        (minimum, maximum): (f32, f32),
119        target_background: Color,
120        surface_background: Color,
121    ) -> Result<Self, LayeredVisualizationError> {
122        let value_extent = scalar_value_range_extent(minimum, maximum)
123            .ok_or(LayeredVisualizationError::InvalidValueRange { minimum, maximum })?;
124        if !target_background.is_normalized() || !surface_background.is_normalized() {
125            return Err(LayeredVisualizationError::InvalidBackground);
126        }
127        Ok(Self {
128            minimum,
129            maximum,
130            value_extent,
131            sampling: ScalarFieldSampling::Linear,
132            blend_mode: BlendMode::Replace,
133            opacity: 1.0,
134            target_background,
135            surface_background,
136        })
137    }
138
139    /// Selects nearest or manual-linear scalar sampling.
140    pub fn with_sampling(mut self, sampling: ScalarFieldSampling) -> Self {
141        self.sampling = sampling;
142        self
143    }
144
145    /// Selects final target composition and validates its opacity.
146    pub fn with_composition(
147        mut self,
148        blend_mode: BlendMode,
149        opacity: f32,
150    ) -> Result<Self, LayeredVisualizationError> {
151        if !opacity.is_finite() || !(0.0..=1.0).contains(&opacity) {
152            return Err(LayeredVisualizationError::InvalidOpacity);
153        }
154        self.blend_mode = blend_mode;
155        self.opacity = opacity;
156        Ok(self)
157    }
158
159    /// Returns the finite scalar range represented by the heatmap.
160    pub fn value_range(self) -> (f32, f32) {
161        (self.minimum, self.maximum)
162    }
163
164    /// Returns the selected scalar sampling mode.
165    pub fn sampling(self) -> ScalarFieldSampling {
166        self.sampling
167    }
168
169    /// Returns final target-to-surface blending.
170    pub fn blend_mode(self) -> BlendMode {
171        self.blend_mode
172    }
173
174    /// Returns final target opacity.
175    pub fn opacity(self) -> f32 {
176        self.opacity
177    }
178}
179
180/// Status, timings, and encoded-work counters for one fused scalar/particle frame.
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub struct LayeredVisualizationReport {
183    report: RenderReport,
184    render_pass_count: usize,
185    draw_call_count: usize,
186}
187
188impl LayeredVisualizationReport {
189    /// Returns whether the surface frame was drawn or temporarily skipped.
190    pub fn status(self) -> RenderStatus {
191        self.report.status()
192    }
193
194    /// Returns CPU-side renderer stage timings.
195    pub fn metrics(self) -> RendererFrameMetrics {
196        self.report.metrics()
197    }
198
199    /// Returns render passes actually encoded for this call.
200    pub const fn render_pass_count(self) -> usize {
201        self.render_pass_count
202    }
203
204    /// Returns draw calls actually encoded for this call.
205    pub const fn draw_call_count(self) -> usize {
206        self.draw_call_count
207    }
208}
209
210/// Failure while drawing a bounded scalar-field and particle composition.
211#[derive(Debug, Clone, Copy, PartialEq)]
212pub enum LayeredVisualizationError {
213    /// At least one resource belongs to another renderer/device.
214    RendererMismatch,
215    /// Scalar endpoints are invalid or their subtraction overflows `f32`.
216    InvalidValueRange {
217        /// Lower scalar endpoint supplied by the host.
218        minimum: f32,
219        /// Upper scalar endpoint supplied by the host.
220        maximum: f32,
221    },
222    /// A clear color is not normalized finite linear RGBA.
223    InvalidBackground,
224    /// Final composition opacity is outside the normalized finite range.
225    InvalidOpacity,
226    /// Camera arithmetic cannot produce finite particle geometry.
227    InvalidGeometryTransform,
228    /// Particle preparation, surface acquisition, or frame presentation failed.
229    Frame(RendererFrameError),
230}
231
232impl fmt::Display for LayeredVisualizationError {
233    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
234        match self {
235            Self::RendererMismatch => {
236                write!(formatter, "visual resources belong to another renderer")
237            }
238            Self::InvalidValueRange { minimum, maximum } => {
239                write!(formatter, "invalid scalar value range {minimum}..{maximum}")
240            }
241            Self::InvalidBackground => {
242                write!(
243                    formatter,
244                    "visualization colors must be normalized linear RGBA"
245                )
246            }
247            Self::InvalidOpacity => write!(formatter, "visualization opacity must be in 0..=1"),
248            Self::InvalidGeometryTransform => {
249                write!(formatter, "particle camera transform is invalid")
250            }
251            Self::Frame(error) => write!(formatter, "visualization frame failed: {error}"),
252        }
253    }
254}
255
256impl Error for LayeredVisualizationError {}
257
258impl WgpuRenderer {
259    /// Draws a heatmap, overlays a budgeted particle field, and presents the
260    /// target with one command encoder and one queue submission.
261    ///
262    /// This fused path avoids synchronously submitting each layer and leaves
263    /// substantially more CPU time for an expensive host simulation. The
264    /// target should have the presentation surface's aspect ratio; lowering
265    /// both dimensions proportionally bounds raster cost without changing the
266    /// logical camera contract.
267    pub fn render_layered_visualization(
268        &mut self,
269        target: &RenderTarget2d,
270        scalar: &ScalarFieldTexture,
271        color_map: &ColorMap,
272        particles: &mut ParticleField2d,
273        camera: &Camera2d,
274        options: LayeredVisualizationOptions,
275    ) -> Result<LayeredVisualizationReport, LayeredVisualizationError> {
276        let frame_started_at = Instant::now();
277        let preparation_started_at = Instant::now();
278        self.validate_render_target(target)
279            .map_err(|_| LayeredVisualizationError::RendererMismatch)?;
280        self.validate_scalar_field_texture(scalar)
281            .map_err(|_| LayeredVisualizationError::RendererMismatch)?;
282        self.validate_particle_field(particles)
283            .map_err(|_| LayeredVisualizationError::RendererMismatch)?;
284        if !scalar_normalization_is_portable(scalar, options.minimum, options.value_extent) {
285            return Err(LayeredVisualizationError::InvalidValueRange {
286                minimum: options.minimum,
287                maximum: options.maximum,
288            });
289        }
290
291        // Particle validation and all fallible host reservation complete before
292        // any heatmap cache or queue mutation.
293        let preparation = self
294            .prepare_particle_draw(particles, *camera)
295            .map_err(|error| match error {
296                RendererFrameError::InvalidGeometryTransform => {
297                    LayeredVisualizationError::InvalidGeometryTransform
298                }
299                other => LayeredVisualizationError::Frame(other),
300            })?;
301        let preparation_duration = preparation_started_at.elapsed();
302
303        let acquire_started_at = Instant::now();
304        let surface_texture = match self.surface.get_current_texture() {
305            wgpu::CurrentSurfaceTexture::Success(texture)
306            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
307            wgpu::CurrentSurfaceTexture::Timeout => {
308                particles.statistics = preparation.statistics;
309                return Ok(skipped_layered_report(layered_report(
310                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
311                    preparation_duration,
312                    Duration::ZERO,
313                    Duration::ZERO,
314                    acquire_started_at.elapsed(),
315                    Duration::ZERO,
316                    frame_started_at.elapsed(),
317                )));
318            }
319            wgpu::CurrentSurfaceTexture::Occluded => {
320                particles.statistics = preparation.statistics;
321                return Ok(skipped_layered_report(layered_report(
322                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
323                    preparation_duration,
324                    Duration::ZERO,
325                    Duration::ZERO,
326                    acquire_started_at.elapsed(),
327                    Duration::ZERO,
328                    frame_started_at.elapsed(),
329                )));
330            }
331            wgpu::CurrentSurfaceTexture::Outdated => {
332                let _ = self.resize(self.config.width, self.config.height);
333                particles.statistics = preparation.statistics;
334                return Ok(skipped_layered_report(layered_report(
335                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
336                    preparation_duration,
337                    Duration::ZERO,
338                    Duration::ZERO,
339                    acquire_started_at.elapsed(),
340                    Duration::ZERO,
341                    frame_started_at.elapsed(),
342                )));
343            }
344            wgpu::CurrentSurfaceTexture::Lost => {
345                return Err(LayeredVisualizationError::Frame(
346                    RendererFrameError::Surface(RendererSurfaceStatus::Lost),
347                ));
348            }
349            wgpu::CurrentSurfaceTexture::Validation => {
350                return Err(LayeredVisualizationError::Frame(
351                    RendererFrameError::Surface(RendererSurfaceStatus::Validation),
352                ));
353            }
354        };
355        let surface_acquire = acquire_started_at.elapsed();
356        let (particle_upload, camera_uniform_upload) =
357            self.upload_particle_draw(particles, preparation);
358        let upload_started_at = Instant::now();
359        let color_map_view = self.color_map_view(color_map);
360        let scalar_view = scalar
361            .texture
362            .create_view(&wgpu::TextureViewDescriptor::default());
363        self.queue.write_buffer(
364            &self.heatmap_uniform_buffer,
365            0,
366            bytemuck::bytes_of(&HeatmapUniform::new(
367                options.minimum,
368                options.value_extent,
369                scalar.width(),
370                scalar.height(),
371                options.sampling,
372            )),
373        );
374        let heatmap_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
375            label: Some("sim-engine layered heatmap bind group"),
376            layout: &self.heatmap_bind_group_layout,
377            entries: &[
378                wgpu::BindGroupEntry {
379                    binding: 0,
380                    resource: wgpu::BindingResource::TextureView(&scalar_view),
381                },
382                wgpu::BindGroupEntry {
383                    binding: 1,
384                    resource: wgpu::BindingResource::TextureView(&color_map_view),
385                },
386                wgpu::BindGroupEntry {
387                    binding: 2,
388                    resource: self.heatmap_uniform_buffer.as_entire_binding(),
389                },
390            ],
391        });
392        self.queue.write_buffer(
393            &self.composition_pipelines.uniform_buffer,
394            0,
395            bytemuck::bytes_of(&CompositeUniform::full_surface(options.opacity)),
396        );
397        let composition_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
398            label: Some("sim-engine layered composition bind group"),
399            layout: &self.composition_pipelines.bind_group_layout,
400            entries: &[
401                wgpu::BindGroupEntry {
402                    binding: 0,
403                    resource: wgpu::BindingResource::TextureView(&target.view),
404                },
405                wgpu::BindGroupEntry {
406                    binding: 1,
407                    resource: self
408                        .composition_pipelines
409                        .uniform_buffer
410                        .as_entire_binding(),
411                },
412            ],
413        });
414        let upload = combined_layered_upload(particle_upload, upload_started_at.elapsed());
415        let encode_started_at = Instant::now();
416        let surface_view = surface_texture
417            .texture
418            .create_view(&wgpu::TextureViewDescriptor::default());
419        let (view, resolve_target) = match &self.multisample_target {
420            Some(multisample_target) => (&multisample_target.view, Some(&surface_view)),
421            None => (&surface_view, None),
422        };
423        let mut encoder = self
424            .device
425            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
426                label: Some("sim-engine layered visualization encoder"),
427            });
428        let mut render_pass_count = 0_usize;
429        let mut draw_call_count = 0_usize;
430        {
431            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
432                label: Some("sim-engine layered heatmap pass"),
433                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
434                    view: &target.view,
435                    depth_slice: None,
436                    resolve_target: None,
437                    ops: wgpu::Operations {
438                        load: wgpu::LoadOp::Clear(premultiplied_wgpu_color(
439                            options.target_background,
440                        )),
441                        store: wgpu::StoreOp::Store,
442                    },
443                })],
444                depth_stencil_attachment: None,
445                timestamp_writes: None,
446                occlusion_query_set: None,
447                multiview_mask: None,
448            });
449            pass.set_pipeline(&self.target_heatmap_pipeline);
450            pass.set_bind_group(0, &heatmap_bind_group, &[]);
451            pass.draw(0..6, 0..1);
452            render_pass_count += 1;
453            draw_call_count += 1;
454        }
455        {
456            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
457                label: Some("sim-engine layered particle pass"),
458                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
459                    view: &target.view,
460                    depth_slice: None,
461                    resolve_target: None,
462                    ops: wgpu::Operations {
463                        load: wgpu::LoadOp::Load,
464                        store: wgpu::StoreOp::Store,
465                    },
466                })],
467                depth_stencil_attachment: None,
468                timestamp_writes: None,
469                occlusion_query_set: None,
470                multiview_mask: None,
471            });
472            if preparation.visible_count > 0 {
473                pass.set_pipeline(&self.target_particle_pipeline);
474                pass.set_bind_group(0, &self.camera_bind_group, &[]);
475                pass.set_vertex_buffer(0, self.particle_unit_buffer.slice(..));
476                pass.set_vertex_buffer(1, particles.instance_buffer.slice(..));
477                pass.draw(0..6, 0..preparation.visible_count as u32);
478                draw_call_count += 1;
479            }
480            render_pass_count += 1;
481        }
482        {
483            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
484                label: Some("sim-engine layered composition pass"),
485                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
486                    view,
487                    depth_slice: None,
488                    resolve_target,
489                    ops: wgpu::Operations {
490                        load: wgpu::LoadOp::Clear(options.surface_background.to_wgpu()),
491                        store: wgpu::StoreOp::Store,
492                    },
493                })],
494                depth_stencil_attachment: None,
495                timestamp_writes: None,
496                occlusion_query_set: None,
497                multiview_mask: None,
498            });
499            pass.set_pipeline(self.composition_pipelines.pipeline(options.blend_mode));
500            pass.set_bind_group(0, &composition_bind_group, &[]);
501            pass.draw(0..6, 0..1);
502            render_pass_count += 1;
503            draw_call_count += 1;
504        }
505        self.queue.submit([encoder.finish()]);
506        self.notify_before_present();
507        self.queue.present(surface_texture);
508        particles.statistics = ParticleStatistics {
509            rendered: preparation.visible_count,
510            ..preparation.statistics
511        };
512        Ok(LayeredVisualizationReport {
513            report: layered_report(
514                RenderStatus::Drawn,
515                preparation_duration,
516                upload,
517                camera_uniform_upload,
518                surface_acquire,
519                encode_started_at.elapsed(),
520                frame_started_at.elapsed(),
521            ),
522            render_pass_count,
523            draw_call_count,
524        })
525    }
526}
527
528fn skipped_layered_report(report: RenderReport) -> LayeredVisualizationReport {
529    LayeredVisualizationReport {
530        report,
531        render_pass_count: 0,
532        draw_call_count: 0,
533    }
534}
535
536fn layered_report(
537    status: RenderStatus,
538    preparation: Duration,
539    upload: Duration,
540    camera_uniform_upload: Duration,
541    surface_acquire: Duration,
542    encode_submit_present: Duration,
543    total_cpu: Duration,
544) -> RenderReport {
545    render_report(
546        status,
547        preparation,
548        upload,
549        camera_uniform_upload,
550        surface_acquire,
551        encode_submit_present,
552        total_cpu,
553        false,
554        true,
555        TessellationStats::default(),
556    )
557}
558
559fn combined_layered_upload(particle_upload: Duration, remaining_upload: Duration) -> Duration {
560    particle_upload.saturating_add(remaining_upload)
561}
562
563#[cfg(test)]
564mod tests {
565    use super::{combined_layered_upload, layered_report, skipped_layered_report};
566    use crate::{RenderStatus, RendererSurfaceStatus};
567    use std::time::Duration;
568
569    #[test]
570    fn layered_upload_includes_particle_and_composition_uploads() {
571        assert_eq!(
572            combined_layered_upload(Duration::from_millis(7), Duration::from_millis(3)),
573            Duration::from_millis(10)
574        );
575    }
576
577    #[test]
578    fn layered_reports_completed_preparation_for_drawn_and_skipped_frames() {
579        let preparation = Duration::from_millis(4);
580        let drawn = layered_report(
581            RenderStatus::Drawn,
582            preparation,
583            Duration::ZERO,
584            Duration::ZERO,
585            Duration::ZERO,
586            Duration::ZERO,
587            preparation,
588        );
589        let skipped = layered_report(
590            RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
591            preparation,
592            Duration::ZERO,
593            Duration::ZERO,
594            Duration::from_millis(1),
595            Duration::ZERO,
596            Duration::from_millis(5),
597        );
598
599        assert_eq!(drawn.metrics().tessellation(), preparation);
600        assert_eq!(skipped.metrics().tessellation(), preparation);
601        let skipped = skipped_layered_report(skipped);
602        assert_eq!(skipped.render_pass_count(), 0);
603        assert_eq!(skipped.draw_call_count(), 0);
604    }
605}