Skip to main content

viewport_lib/renderer/
mod.rs

1//! `ViewportRenderer` — the main entry point for the viewport library.
2//!
3//! Wraps [`ViewportGpuResources`] and provides `prepare()` / `paint()` methods
4//! that take raw `wgpu` types. GUI framework adapters (e.g. the egui
5//! `CallbackTrait` impl in the application crate) delegate to these methods.
6
7#[macro_use]
8mod types;
9mod picking;
10mod prepare;
11mod render;
12pub mod shader_hashes;
13mod shadows;
14pub mod stats;
15
16pub use self::types::{
17    ClipPlane, ClipVolume, ComputeFilterItem, ComputeFilterKind, FilterMode, FrameData, GlyphItem,
18    GlyphType, LightKind, LightSource, LightingSettings, OverlayQuad, PointCloudItem,
19    PointRenderMode, PolylineItem, PostProcessSettings, ScalarBar, ScalarBarAnchor,
20    ScalarBarOrientation, SceneRenderItem, ShadowFilter, StreamtubeItem, ToneMapping, VolumeItem,
21};
22
23use self::shadows::{compute_cascade_matrix, compute_cascade_splits};
24use self::types::{INSTANCING_THRESHOLD, InstancedBatch};
25use crate::resources::{
26    CameraUniform, ClipPlanesUniform, GridUniform, InstanceData, LightsUniform, ObjectUniform,
27    OutlineObjectBuffers, OutlineUniform, OverlayUniform, PickInstance, SingleLightUniform,
28    ViewportGpuResources,
29};
30
31/// High-level renderer wrapping all GPU resources and providing framework-agnostic
32/// `prepare()` and `paint()` methods.
33pub struct ViewportRenderer {
34    resources: ViewportGpuResources,
35    /// Instanced batches prepared for the current frame. Empty when using per-object path.
36    instanced_batches: Vec<InstancedBatch>,
37    /// Whether the current frame uses the instanced draw path.
38    use_instancing: bool,
39    /// Performance counters from the last frame.
40    last_stats: crate::renderer::stats::FrameStats,
41    /// Last scene generation seen during prepare(). u64::MAX forces rebuild on first frame.
42    last_scene_generation: u64,
43    /// Last selection generation seen during prepare(). u64::MAX forces rebuild on first frame.
44    last_selection_generation: u64,
45    /// Last wireframe mode seen during prepare(). Batch layout differs between solid and wireframe.
46    last_wireframe_mode: bool,
47    /// Last scene_items count seen during prepare(). usize::MAX forces rebuild on first frame.
48    /// Included in cache key so that frustum-culling changes (different visible set, different
49    /// count) correctly invalidate the instance buffer even when scene_generation is stable.
50    last_scene_items_count: usize,
51    /// Cached instance data from last rebuild (mirrors the GPU buffer contents).
52    cached_instance_data: Vec<InstanceData>,
53    /// Cached instanced batch descriptors from last rebuild.
54    cached_instanced_batches: Vec<InstancedBatch>,
55    /// Per-frame point cloud GPU data, rebuilt in prepare(), consumed in paint().
56    point_cloud_gpu_data: Vec<crate::resources::PointCloudGpuData>,
57    /// Per-frame glyph GPU data, rebuilt in prepare(), consumed in paint().
58    glyph_gpu_data: Vec<crate::resources::GlyphGpuData>,
59    /// Per-frame polyline GPU data, rebuilt in prepare(), consumed in paint().
60    polyline_gpu_data: Vec<crate::resources::PolylineGpuData>,
61    /// Per-frame volume GPU data, rebuilt in prepare(), consumed in paint().
62    volume_gpu_data: Vec<crate::resources::VolumeGpuData>,
63    /// Per-frame streamtube GPU data, rebuilt in prepare(), consumed in paint().
64    streamtube_gpu_data: Vec<crate::resources::StreamtubeGpuData>,
65    /// Per-viewport camera uniform buffers and bind groups.
66    ///
67    /// In single-viewport mode only slot 0 is used (same as the legacy
68    /// `resources.camera_bind_group`).  In multi-viewport mode each sub-viewport
69    /// has its own slot so concurrent `prepare` calls don't clobber each other.
70    ///
71    /// The outer Vec is indexed by `FrameData::viewport_index`.  Slots are
72    /// grown lazily in `prepare` via `ensure_viewport_camera_slot`.
73    per_viewport_cameras: Vec<(wgpu::Buffer, wgpu::BindGroup)>,
74    /// Phase G — GPU compute filter results from the last `prepare()` call.
75    ///
76    /// Each entry contains a compacted index buffer + count for one filtered mesh.
77    /// Consumed during `paint()` to override the mesh's default index buffer.
78    /// Cleared and rebuilt each frame.
79    compute_filter_results: Vec<crate::resources::ComputeFilterResult>,
80}
81
82impl ViewportRenderer {
83    /// Create a new renderer with default settings (no MSAA).
84    /// Call once at application startup.
85    pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
86        Self::with_sample_count(device, target_format, 1)
87    }
88
89    /// Create a new renderer with the specified MSAA sample count (1, 2, or 4).
90    ///
91    /// When using MSAA (sample_count > 1), the caller must create multisampled
92    /// color and depth textures and use them as render pass attachments with the
93    /// final surface texture as the resolve target.
94    pub fn with_sample_count(
95        device: &wgpu::Device,
96        target_format: wgpu::TextureFormat,
97        sample_count: u32,
98    ) -> Self {
99        Self {
100            resources: ViewportGpuResources::new(device, target_format, sample_count),
101            instanced_batches: Vec::new(),
102            use_instancing: false,
103            last_stats: crate::renderer::stats::FrameStats::default(),
104            last_scene_generation: u64::MAX,
105            last_selection_generation: u64::MAX,
106            last_wireframe_mode: false,
107            last_scene_items_count: usize::MAX,
108            cached_instance_data: Vec::new(),
109            cached_instanced_batches: Vec::new(),
110            point_cloud_gpu_data: Vec::new(),
111            glyph_gpu_data: Vec::new(),
112            polyline_gpu_data: Vec::new(),
113            volume_gpu_data: Vec::new(),
114            streamtube_gpu_data: Vec::new(),
115            per_viewport_cameras: Vec::new(),
116            compute_filter_results: Vec::new(),
117        }
118    }
119
120    /// Access the underlying GPU resources (e.g. for mesh uploads).
121    pub fn resources(&self) -> &ViewportGpuResources {
122        &self.resources
123    }
124
125    /// Performance counters from the last completed frame.
126    pub fn last_frame_stats(&self) -> crate::renderer::stats::FrameStats {
127        self.last_stats
128    }
129
130    /// Mutable access to the underlying GPU resources (e.g. for mesh uploads).
131    pub fn resources_mut(&mut self) -> &mut ViewportGpuResources {
132        &mut self.resources
133    }
134
135    /// Ensure a per-viewport camera slot exists for `viewport_index`.
136    ///
137    /// Creates a new `(Buffer, BindGroup)` pair that mirrors the layout of the
138    /// shared `resources.camera_bind_group` but with an independent camera
139    /// uniform buffer.  Slots are created lazily and never destroyed (there are
140    /// at most 4 in the current UI: single, split-h top/bottom, quad × 4).
141    fn ensure_viewport_camera_slot(&mut self, device: &wgpu::Device, viewport_index: usize) {
142        while self.per_viewport_cameras.len() <= viewport_index {
143            let buf = device.create_buffer(&wgpu::BufferDescriptor {
144                label: Some("per_viewport_camera_buf"),
145                size: std::mem::size_of::<crate::resources::CameraUniform>() as u64,
146                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
147                mapped_at_creation: false,
148            });
149            // The camera bind group (group 0) binds seven resources.  Only binding 0
150            // (camera uniform) differs per viewport.  Bindings 1-6 (shadow map,
151            // shadow sampler, light uniform, clip planes, shadow atlas info,
152            // clip volume) are shared from the primary resources so all viewports
153            // see the same lighting, shadow, and clip state.
154            let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
155                label: Some("per_viewport_camera_bg"),
156                layout: &self.resources.camera_bind_group_layout,
157                entries: &[
158                    wgpu::BindGroupEntry {
159                        binding: 0,
160                        resource: buf.as_entire_binding(),
161                    },
162                    wgpu::BindGroupEntry {
163                        binding: 1,
164                        resource: wgpu::BindingResource::TextureView(
165                            &self.resources.shadow_map_view,
166                        ),
167                    },
168                    wgpu::BindGroupEntry {
169                        binding: 2,
170                        resource: wgpu::BindingResource::Sampler(&self.resources.shadow_sampler),
171                    },
172                    wgpu::BindGroupEntry {
173                        binding: 3,
174                        resource: self.resources.light_uniform_buf.as_entire_binding(),
175                    },
176                    wgpu::BindGroupEntry {
177                        binding: 4,
178                        resource: self.resources.clip_planes_uniform_buf.as_entire_binding(),
179                    },
180                    wgpu::BindGroupEntry {
181                        binding: 5,
182                        resource: self.resources.shadow_info_buf.as_entire_binding(),
183                    },
184                    wgpu::BindGroupEntry {
185                        binding: 6,
186                        resource: self.resources.clip_volume_uniform_buf.as_entire_binding(),
187                    },
188                ],
189            });
190            self.per_viewport_cameras.push((buf, bg));
191        }
192    }
193
194    /// Return a reference to the camera bind group for the given viewport slot.
195    ///
196    /// Falls back to `resources.camera_bind_group` if no per-viewport slot
197    /// exists (e.g. in single-viewport mode before the first prepare call).
198    fn viewport_camera_bind_group(&self, viewport_index: usize) -> &wgpu::BindGroup {
199        self.per_viewport_cameras
200            .get(viewport_index)
201            .map(|(_, bg)| bg)
202            .unwrap_or(&self.resources.camera_bind_group)
203    }
204}