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