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) source: ColorMap,
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("heatmap_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    value_extent: f32,
107    sampling: ScalarFieldSampling,
108    blend_mode: BlendMode,
109    opacity: f32,
110    target_background: Color,
111    surface_background: Color,
112}
113
114impl LayeredVisualizationOptions {
115    /// Creates settings with linear field sampling and opaque replacement.
116    pub fn new(
117        (minimum, maximum): (f32, f32),
118        target_background: Color,
119        surface_background: Color,
120    ) -> Result<Self, LayeredVisualizationError> {
121        let value_extent = scalar_value_range_extent(minimum, maximum)
122            .ok_or(LayeredVisualizationError::InvalidValueRange { minimum, maximum })?;
123        if !target_background.is_normalized() || !surface_background.is_normalized() {
124            return Err(LayeredVisualizationError::InvalidBackground);
125        }
126        Ok(Self {
127            minimum,
128            value_extent,
129            sampling: ScalarFieldSampling::Linear,
130            blend_mode: BlendMode::Replace,
131            opacity: 1.0,
132            target_background,
133            surface_background,
134        })
135    }
136
137    /// Selects nearest or manual-linear scalar sampling.
138    pub fn with_sampling(mut self, sampling: ScalarFieldSampling) -> Self {
139        self.sampling = sampling;
140        self
141    }
142
143    /// Selects final target composition and validates its opacity.
144    pub fn with_composition(
145        mut self,
146        blend_mode: BlendMode,
147        opacity: f32,
148    ) -> Result<Self, LayeredVisualizationError> {
149        if !opacity.is_finite() || !(0.0..=1.0).contains(&opacity) {
150            return Err(LayeredVisualizationError::InvalidOpacity);
151        }
152        self.blend_mode = blend_mode;
153        self.opacity = opacity;
154        Ok(self)
155    }
156
157    /// Returns the finite scalar range represented by the heatmap.
158    pub fn value_range(self) -> (f32, f32) {
159        (self.minimum, self.minimum + self.value_extent)
160    }
161
162    /// Returns the selected scalar sampling mode.
163    pub fn sampling(self) -> ScalarFieldSampling {
164        self.sampling
165    }
166
167    /// Returns final target-to-surface blending.
168    pub fn blend_mode(self) -> BlendMode {
169        self.blend_mode
170    }
171
172    /// Returns final target opacity.
173    pub fn opacity(self) -> f32 {
174        self.opacity
175    }
176}
177
178/// Failure while drawing a bounded scalar-field and particle composition.
179#[derive(Debug, Clone, Copy, PartialEq)]
180pub enum LayeredVisualizationError {
181    /// At least one resource belongs to another renderer/device.
182    RendererMismatch,
183    /// Scalar endpoints are invalid or their subtraction overflows `f32`.
184    InvalidValueRange {
185        /// Lower scalar endpoint supplied by the host.
186        minimum: f32,
187        /// Upper scalar endpoint supplied by the host.
188        maximum: f32,
189    },
190    /// A clear color contains NaN or infinity.
191    InvalidBackground,
192    /// Final composition opacity is outside the normalized finite range.
193    InvalidOpacity,
194    /// Camera arithmetic cannot produce finite particle geometry.
195    InvalidGeometryTransform,
196    /// Surface acquisition or presentation failed.
197    Frame(RendererFrameError),
198}
199
200impl fmt::Display for LayeredVisualizationError {
201    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
202        match self {
203            Self::RendererMismatch => {
204                write!(formatter, "visual resources belong to another renderer")
205            }
206            Self::InvalidValueRange { minimum, maximum } => {
207                write!(formatter, "invalid scalar value range {minimum}..{maximum}")
208            }
209            Self::InvalidBackground => {
210                write!(
211                    formatter,
212                    "visualization colors must be normalized linear RGBA"
213                )
214            }
215            Self::InvalidOpacity => write!(formatter, "visualization opacity must be in 0..=1"),
216            Self::InvalidGeometryTransform => {
217                write!(formatter, "particle camera transform is invalid")
218            }
219            Self::Frame(error) => write!(formatter, "visualization frame failed: {error}"),
220        }
221    }
222}
223
224impl Error for LayeredVisualizationError {}
225
226impl WgpuRenderer {
227    /// Draws a heatmap, overlays a budgeted particle field, and presents the
228    /// target with one command encoder and one queue submission.
229    ///
230    /// This fused path avoids synchronously submitting each layer and leaves
231    /// substantially more CPU time for an expensive host simulation. The
232    /// target should have the presentation surface's aspect ratio; lowering
233    /// both dimensions proportionally bounds raster cost without changing the
234    /// logical camera contract.
235    pub fn render_layered_visualization(
236        &mut self,
237        target: &RenderTarget2d,
238        scalar: &ScalarFieldTexture,
239        color_map: &ColorMap,
240        particles: &mut ParticleField2d,
241        camera: &Camera2d,
242        options: LayeredVisualizationOptions,
243    ) -> Result<RenderReport, LayeredVisualizationError> {
244        self.validate_render_target(target)
245            .map_err(|_| LayeredVisualizationError::RendererMismatch)?;
246        self.validate_scalar_field_texture(scalar)
247            .map_err(|_| LayeredVisualizationError::RendererMismatch)?;
248        self.validate_particle_field(particles)
249            .map_err(|_| LayeredVisualizationError::RendererMismatch)?;
250
251        let frame_started_at = Instant::now();
252        let upload_started_at = Instant::now();
253        let color_map_view = self.color_map_view(color_map);
254        let scalar_view = scalar
255            .texture
256            .create_view(&wgpu::TextureViewDescriptor::default());
257        self.queue.write_buffer(
258            &self.heatmap_uniform_buffer,
259            0,
260            bytemuck::bytes_of(&HeatmapUniform {
261                value_range: [options.minimum, options.value_extent, 0.0, 0.0],
262                dimensions: [
263                    scalar.width() as u32,
264                    scalar.height() as u32,
265                    options.sampling.shader_value(),
266                    0,
267                ],
268            }),
269        );
270        let heatmap_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
271            label: Some("sim-engine layered heatmap bind group"),
272            layout: &self.heatmap_bind_group_layout,
273            entries: &[
274                wgpu::BindGroupEntry {
275                    binding: 0,
276                    resource: wgpu::BindingResource::TextureView(&scalar_view),
277                },
278                wgpu::BindGroupEntry {
279                    binding: 1,
280                    resource: wgpu::BindingResource::TextureView(&color_map_view),
281                },
282                wgpu::BindGroupEntry {
283                    binding: 2,
284                    resource: self.heatmap_uniform_buffer.as_entire_binding(),
285                },
286            ],
287        });
288        self.queue.write_buffer(
289            &self.composition_pipelines.uniform_buffer,
290            0,
291            bytemuck::bytes_of(&CompositeUniform {
292                opacity: [options.opacity, 0.0, 0.0, 0.0],
293            }),
294        );
295        let composition_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
296            label: Some("sim-engine layered composition bind group"),
297            layout: &self.composition_pipelines.bind_group_layout,
298            entries: &[
299                wgpu::BindGroupEntry {
300                    binding: 0,
301                    resource: wgpu::BindingResource::TextureView(&target.view),
302                },
303                wgpu::BindGroupEntry {
304                    binding: 1,
305                    resource: self
306                        .composition_pipelines
307                        .uniform_buffer
308                        .as_entire_binding(),
309                },
310            ],
311        });
312        let preparation = self
313            .prepare_particle_draw(particles, *camera)
314            .map_err(|error| match error {
315                RendererFrameError::InvalidGeometryTransform => {
316                    LayeredVisualizationError::InvalidGeometryTransform
317                }
318                other => LayeredVisualizationError::Frame(other),
319            })?;
320        let upload = upload_started_at.elapsed();
321
322        let acquire_started_at = Instant::now();
323        let surface_texture = match self.surface.get_current_texture() {
324            wgpu::CurrentSurfaceTexture::Success(texture)
325            | wgpu::CurrentSurfaceTexture::Suboptimal(texture) => texture,
326            wgpu::CurrentSurfaceTexture::Timeout => {
327                particles.statistics.rendered = 0;
328                return Ok(layered_report(
329                    RenderStatus::Skipped(RendererSurfaceStatus::Timeout),
330                    upload,
331                    preparation.camera_uniform_upload,
332                    acquire_started_at.elapsed(),
333                    Duration::ZERO,
334                    frame_started_at.elapsed(),
335                ));
336            }
337            wgpu::CurrentSurfaceTexture::Occluded => {
338                particles.statistics.rendered = 0;
339                return Ok(layered_report(
340                    RenderStatus::Skipped(RendererSurfaceStatus::Occluded),
341                    upload,
342                    preparation.camera_uniform_upload,
343                    acquire_started_at.elapsed(),
344                    Duration::ZERO,
345                    frame_started_at.elapsed(),
346                ));
347            }
348            wgpu::CurrentSurfaceTexture::Outdated => {
349                self.resize(self.config.width, self.config.height);
350                particles.statistics.rendered = 0;
351                return Ok(layered_report(
352                    RenderStatus::Skipped(RendererSurfaceStatus::Outdated),
353                    upload,
354                    preparation.camera_uniform_upload,
355                    acquire_started_at.elapsed(),
356                    Duration::ZERO,
357                    frame_started_at.elapsed(),
358                ));
359            }
360            wgpu::CurrentSurfaceTexture::Lost => {
361                return Err(LayeredVisualizationError::Frame(
362                    RendererFrameError::Surface(RendererSurfaceStatus::Lost),
363                ));
364            }
365            wgpu::CurrentSurfaceTexture::Validation => {
366                return Err(LayeredVisualizationError::Frame(
367                    RendererFrameError::Surface(RendererSurfaceStatus::Validation),
368                ));
369            }
370        };
371        let surface_acquire = acquire_started_at.elapsed();
372        let encode_started_at = Instant::now();
373        let surface_view = surface_texture
374            .texture
375            .create_view(&wgpu::TextureViewDescriptor::default());
376        let (view, resolve_target) = match &self.multisample_target {
377            Some(multisample_target) => (&multisample_target.view, Some(&surface_view)),
378            None => (&surface_view, None),
379        };
380        let mut encoder = self
381            .device
382            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
383                label: Some("sim-engine layered visualization encoder"),
384            });
385        {
386            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
387                label: Some("sim-engine layered heatmap pass"),
388                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
389                    view: &target.view,
390                    depth_slice: None,
391                    resolve_target: None,
392                    ops: wgpu::Operations {
393                        load: wgpu::LoadOp::Clear(premultiplied_wgpu_color(
394                            options.target_background,
395                        )),
396                        store: wgpu::StoreOp::Store,
397                    },
398                })],
399                depth_stencil_attachment: None,
400                timestamp_writes: None,
401                occlusion_query_set: None,
402                multiview_mask: None,
403            });
404            pass.set_pipeline(&self.target_heatmap_pipeline);
405            pass.set_bind_group(0, &heatmap_bind_group, &[]);
406            pass.draw(0..6, 0..1);
407        }
408        {
409            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
410                label: Some("sim-engine layered particle pass"),
411                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
412                    view: &target.view,
413                    depth_slice: None,
414                    resolve_target: None,
415                    ops: wgpu::Operations {
416                        load: wgpu::LoadOp::Load,
417                        store: wgpu::StoreOp::Store,
418                    },
419                })],
420                depth_stencil_attachment: None,
421                timestamp_writes: None,
422                occlusion_query_set: None,
423                multiview_mask: None,
424            });
425            if preparation.visible_count > 0 {
426                pass.set_pipeline(&self.target_particle_pipeline);
427                pass.set_bind_group(0, &self.camera_bind_group, &[]);
428                pass.set_vertex_buffer(0, self.particle_unit_buffer.slice(..));
429                pass.set_vertex_buffer(1, particles.instance_buffer.slice(..));
430                pass.draw(0..6, 0..preparation.visible_count as u32);
431            }
432        }
433        {
434            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
435                label: Some("sim-engine layered composition pass"),
436                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
437                    view,
438                    depth_slice: None,
439                    resolve_target,
440                    ops: wgpu::Operations {
441                        load: wgpu::LoadOp::Clear(options.surface_background.to_wgpu()),
442                        store: wgpu::StoreOp::Store,
443                    },
444                })],
445                depth_stencil_attachment: None,
446                timestamp_writes: None,
447                occlusion_query_set: None,
448                multiview_mask: None,
449            });
450            pass.set_pipeline(self.composition_pipelines.pipeline(options.blend_mode));
451            pass.set_bind_group(0, &composition_bind_group, &[]);
452            pass.draw(0..6, 0..1);
453        }
454        self.queue.submit([encoder.finish()]);
455        self.queue.present(surface_texture);
456        particles.statistics.rendered = preparation.visible_count;
457        Ok(layered_report(
458            RenderStatus::Drawn,
459            upload,
460            preparation.camera_uniform_upload,
461            surface_acquire,
462            encode_started_at.elapsed(),
463            frame_started_at.elapsed(),
464        ))
465    }
466}
467
468fn layered_report(
469    status: RenderStatus,
470    upload: Duration,
471    camera_uniform_upload: Duration,
472    surface_acquire: Duration,
473    encode_submit_present: Duration,
474    total_cpu: Duration,
475) -> RenderReport {
476    render_report(
477        status,
478        Duration::ZERO,
479        upload,
480        camera_uniform_upload,
481        surface_acquire,
482        encode_submit_present,
483        total_cpu,
484        false,
485        true,
486        TessellationStats::default(),
487    )
488}