1use cadkit_scene::{Mesh3d, MeshBudget, MeshScene, relative_positions};
4use wgpu::util::DeviceExt;
5
6use crate::{GpuError, check, scopes};
7
8const VERTEX_BYTES: usize = 28;
10const MAX_SCENE_VERTICES: usize = 8_000_000;
13const MAX_SCENE_TRIANGLES: usize = 16_000_000;
14
15#[derive(Debug, Clone, Copy, PartialEq)]
17#[non_exhaustive]
18pub struct OrbitCamera {
19 pub target: [f64; 3],
21 pub yaw: f64,
23 pub pitch: f64,
25 pub distance: f64,
27 pub vertical_fov: f64,
29}
30
31impl OrbitCamera {
32 pub fn new(target: [f64; 3], yaw: f64, pitch: f64, distance: f64, vertical_fov: f64) -> Self {
34 Self {
35 target,
36 yaw,
37 pitch,
38 distance,
39 vertical_fov,
40 }
41 }
42
43 pub fn matrix(&self, aspect: f32) -> Result<[f32; 16], GpuError> {
45 self.matrix_relative(aspect, self.target, 1e-4)
46 }
47
48 pub fn matrix_relative(
51 &self,
52 aspect: f32,
53 origin: [f64; 3],
54 max_coordinate_error: f64,
55 ) -> Result<[f32; 16], GpuError> {
56 if !self.yaw.is_finite()
57 || !self.target.iter().all(|v| v.is_finite())
58 || !self.pitch.is_finite()
59 || !self.distance.is_finite()
60 || self.distance <= 0.
61 || !self.vertical_fov.is_finite()
62 || self.vertical_fov <= 0.01
63 || self.vertical_fov >= 3.
64 || !aspect.is_finite()
65 || aspect <= 0.
66 || self.pitch.abs() >= std::f64::consts::FRAC_PI_2 - 1e-4
67 {
68 return Err(GpuError::InvalidCamera);
69 }
70 let radius = self.distance as f32;
71 if !radius.is_finite() || !(1e-5..=1e12).contains(&radius) {
72 return Err(GpuError::CameraRange);
73 }
74 let target = camera_offset(self.target, origin, max_coordinate_error)?;
75 let target = glam::Vec3::from_array(target);
76 let eye = glam::Vec3::new(
77 (self.yaw.cos() * self.pitch.cos()) as f32,
78 (self.yaw.sin() * self.pitch.cos()) as f32,
79 self.pitch.sin() as f32,
80 ) * radius;
81 let view = glam::camera::rh::view::look_at_mat4(eye, glam::Vec3::ZERO, glam::Vec3::Z)
82 * glam::Mat4::from_translation(-target);
83 let projection = glam::camera::rh::proj::directx::perspective(
84 self.vertical_fov as f32,
85 aspect,
86 (radius * 0.001).max(1e-6),
87 radius * 100.,
88 );
89 Ok((projection * view).to_cols_array())
90 }
91}
92
93fn camera_offset(target: [f64; 3], origin: [f64; 3], max_error: f64) -> Result<[f32; 3], GpuError> {
94 if !max_error.is_finite() || max_error <= 0. {
95 return Err(GpuError::CameraRange);
96 }
97 let mut local = [0f32; 3];
98 for ((slot, coordinate), start) in local.iter_mut().zip(target).zip(origin) {
99 let delta = coordinate - start;
100 let virtual_start = coordinate - delta;
101 let virtual_coordinate = delta + virtual_start;
102 let subtraction_error = (coordinate - virtual_coordinate) + (virtual_start - start);
103 let encoded = delta as f32;
104 let error = (subtraction_error.abs() + (delta - f64::from(encoded)).abs()).next_up();
105 let max_offset = max_error / f64::from(f32::EPSILON) * 0.5;
108 if !delta.is_finite()
109 || !encoded.is_finite()
110 || !error.is_finite()
111 || error > max_error
112 || delta.abs() > max_offset
113 {
114 return Err(GpuError::CameraRange);
115 }
116 *slot = encoded;
117 }
118 Ok(local)
119}
120
121pub fn mesh_budget(device: &wgpu::Device) -> MeshBudget {
125 let limit = usize::try_from(device.limits().max_buffer_size).unwrap_or(usize::MAX);
126 let default = MeshBudget::default();
127 MeshBudget::new(
128 (limit / VERTEX_BYTES)
129 .min(MAX_SCENE_VERTICES)
130 .max(default.max_vertices),
131 (limit / (3 * std::mem::size_of::<u32>()))
132 .min(MAX_SCENE_TRIANGLES)
133 .max(default.max_triangles),
134 )
135}
136
137pub struct MeshRenderer {
139 pipeline: wgpu::RenderPipeline,
140 layout: wgpu::BindGroupLayout,
141}
142
143pub struct PreparedMeshes {
145 vertices: wgpu::Buffer,
146 indices: wgpu::Buffer,
147 camera: wgpu::Buffer,
148 bind_group: wgpu::BindGroup,
149 index_count: u32,
150 source: Vec<Mesh3d>,
151 revision: u64,
152 origin: [f64; 3],
153}
154
155impl MeshRenderer {
156 pub async fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Result<Self, GpuError> {
158 let (validation, allocation) = scopes(device);
159 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
160 label: Some("cadkit mesh shader"),
161 source: wgpu::ShaderSource::Wgsl(include_str!("mesh.wgsl").into()),
162 });
163 let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
164 label: Some("cadkit mesh camera"),
165 entries: &[wgpu::BindGroupLayoutEntry {
166 binding: 0,
167 visibility: wgpu::ShaderStages::VERTEX,
168 ty: wgpu::BindingType::Buffer {
169 ty: wgpu::BufferBindingType::Uniform,
170 has_dynamic_offset: false,
171 min_binding_size: None,
172 },
173 count: None,
174 }],
175 });
176 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
177 label: Some("cadkit mesh pipeline"),
178 bind_group_layouts: &[Some(&layout)],
179 immediate_size: 0,
180 });
181 let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
182 label: Some("cadkit mesh"),
183 layout: Some(&pipeline_layout),
184 vertex: wgpu::VertexState {
185 module: &shader,
186 entry_point: Some("vs_main"),
187 compilation_options: Default::default(),
188 buffers: &[Some(wgpu::VertexBufferLayout {
189 array_stride: VERTEX_BYTES as u64,
190 step_mode: wgpu::VertexStepMode::Vertex,
191 attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x4],
192 })],
193 },
194 primitive: wgpu::PrimitiveState {
195 cull_mode: None,
196 ..Default::default()
197 },
198 depth_stencil: Some(wgpu::DepthStencilState {
199 format: wgpu::TextureFormat::Depth32Float,
200 depth_write_enabled: Some(true),
201 depth_compare: Some(wgpu::CompareFunction::Less),
202 stencil: Default::default(),
203 bias: Default::default(),
204 }),
205 multisample: Default::default(),
206 fragment: Some(wgpu::FragmentState {
207 module: &shader,
208 entry_point: Some("fs_main"),
209 compilation_options: Default::default(),
210 targets: &[Some(wgpu::ColorTargetState {
211 format,
212 blend: None,
213 write_mask: wgpu::ColorWrites::ALL,
214 })],
215 }),
216 multiview_mask: None,
217 cache: None,
218 });
219 check(validation, allocation).await?;
220 Ok(Self { pipeline, layout })
221 }
222
223 pub async fn prepare(
225 &self,
226 device: &wgpu::Device,
227 scene: &MeshScene,
228 camera: OrbitCamera,
229 aspect: f32,
230 max_coordinate_error: f64,
231 ) -> Result<PreparedMeshes, GpuError> {
232 self.prepare_scene(device, scene, camera, aspect, max_coordinate_error, false)
233 .await
234 }
235
236 pub async fn prepare_preview(
239 &self,
240 device: &wgpu::Device,
241 scene: &MeshScene,
242 camera: OrbitCamera,
243 aspect: f32,
244 max_coordinate_error: f64,
245 ) -> Result<PreparedMeshes, GpuError> {
246 self.prepare_scene(device, scene, camera, aspect, max_coordinate_error, true)
247 .await
248 }
249
250 async fn prepare_scene(
251 &self,
252 device: &wgpu::Device,
253 scene: &MeshScene,
254 camera: OrbitCamera,
255 aspect: f32,
256 max_coordinate_error: f64,
257 allow_partial: bool,
258 ) -> Result<PreparedMeshes, GpuError> {
259 if !allow_partial && !scene.complete {
260 return Err(GpuError::IncompleteScene);
261 }
262 let matrix = camera.matrix(aspect)?;
263 let mut vertices = Vec::new();
264 let mut indices = Vec::new();
265 let mut vertex_count = 0u32;
266 for mesh in &scene.meshes {
267 let (encoded_vertices, encoded_indices) =
268 encode_mesh(mesh, camera.target, max_coordinate_error, vertex_count)?;
269 vertex_count = u32::try_from(mesh.positions.len())
270 .ok()
271 .and_then(|n| vertex_count.checked_add(n))
272 .ok_or(GpuError::BufferLimit)?;
273 vertices.extend(encoded_vertices);
274 indices.extend(encoded_indices);
275 }
276 if vertices.is_empty() || indices.is_empty() {
277 return Err(GpuError::EmptyScene);
278 }
279 let index_bytes: Vec<u8> = indices.iter().flat_map(|i| i.to_le_bytes()).collect();
280 let limit = device.limits().max_buffer_size;
281 if vertices.len() as u64 > limit || index_bytes.len() as u64 > limit {
282 return Err(GpuError::BufferLimit);
283 }
284 let index_count = u32::try_from(indices.len()).map_err(|_| GpuError::BufferLimit)?;
285 let (validation, allocation) = scopes(device);
286 let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
287 label: Some("cadkit mesh vertices"),
288 contents: &vertices,
289 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
290 });
291 let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
292 label: Some("cadkit mesh indices"),
293 contents: &index_bytes,
294 usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
295 });
296 let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
297 label: Some("cadkit mesh camera"),
298 contents: &matrix_bytes(&matrix),
299 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
300 });
301 let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
302 label: Some("cadkit mesh camera"),
303 layout: &self.layout,
304 entries: &[wgpu::BindGroupEntry {
305 binding: 0,
306 resource: uniform.as_entire_binding(),
307 }],
308 });
309 check(validation, allocation).await?;
310 Ok(PreparedMeshes {
311 vertices: vertex_buffer,
312 indices: index_buffer,
313 camera: uniform,
314 bind_group,
315 index_count,
316 source: scene.meshes.clone(),
317 revision: scene.revision,
318 origin: camera.target,
319 })
320 }
321
322 pub fn paint(&self, pass: &mut wgpu::RenderPass<'_>, prepared: &PreparedMeshes) {
324 pass.set_pipeline(&self.pipeline);
325 pass.set_bind_group(0, &prepared.bind_group, &[]);
326 pass.set_vertex_buffer(0, prepared.vertices.slice(..));
327 pass.set_index_buffer(prepared.indices.slice(..), wgpu::IndexFormat::Uint32);
328 pass.draw_indexed(0..prepared.index_count, 0, 0..1);
329 }
330}
331
332impl PreparedMeshes {
333 pub fn revision(&self) -> u64 {
335 self.revision
336 }
337
338 pub fn origin(&self) -> [f64; 3] {
340 self.origin
341 }
342
343 pub fn update_meshes(
347 &mut self,
348 queue: &wgpu::Queue,
349 scene: &MeshScene,
350 max_error: f64,
351 ) -> Result<bool, GpuError> {
352 if self.source.len() != scene.meshes.len()
353 || self.source.iter().zip(&scene.meshes).any(|(old, new)| {
354 old.id != new.id
355 || old.positions.len() != new.positions.len()
356 || old.triangles.len() != new.triangles.len()
357 })
358 {
359 return Ok(false);
360 }
361 let mut updates = Vec::new();
362 let mut vertex_offset = 0usize;
363 let mut index_offset = 0usize;
364 for (index, (old, new)) in self.source.iter().zip(&scene.meshes).enumerate() {
365 if old != new {
366 let base = u32::try_from(vertex_offset).map_err(|_| GpuError::BufferLimit)?;
367 let (vertices, indices) = encode_mesh(new, self.origin, max_error, base)?;
368 updates.push((index, vertex_offset, index_offset, vertices, indices));
369 }
370 vertex_offset += new.positions.len();
371 index_offset += new.triangles.len() * 3;
372 }
373 for (index, vertex_offset, index_offset, vertices, indices) in updates {
374 if !vertices.is_empty() {
375 queue.write_buffer(
376 &self.vertices,
377 (vertex_offset * VERTEX_BYTES) as u64,
378 &vertices,
379 );
380 }
381 if !indices.is_empty() {
382 let bytes: Vec<u8> = indices.iter().flat_map(|i| i.to_le_bytes()).collect();
383 queue.write_buffer(
384 &self.indices,
385 (index_offset * std::mem::size_of::<u32>()) as u64,
386 &bytes,
387 );
388 }
389 if let (Some(slot), Some(mesh)) = (self.source.get_mut(index), scene.meshes.get(index))
390 {
391 slot.clone_from(mesh);
392 }
393 }
394 self.revision = scene.revision;
395 Ok(true)
396 }
397
398 pub fn update_camera(
400 &self,
401 queue: &wgpu::Queue,
402 camera: OrbitCamera,
403 aspect: f32,
404 max_coordinate_error: f64,
405 ) -> Result<(), GpuError> {
406 let matrix = camera.matrix_relative(aspect, self.origin, max_coordinate_error)?;
407 queue.write_buffer(&self.camera, 0, &matrix_bytes(&matrix));
408 Ok(())
409 }
410
411 pub fn can_reuse_origin(&self, camera: OrbitCamera, max_coordinate_error: f64) -> bool {
414 camera_offset(camera.target, self.origin, max_coordinate_error).is_ok()
415 }
416}
417
418fn matrix_bytes(matrix: &[f32; 16]) -> Vec<u8> {
419 matrix.iter().flat_map(|v| v.to_le_bytes()).collect()
420}
421
422fn encode_mesh(
424 mesh: &Mesh3d,
425 origin: [f64; 3],
426 max_error: f64,
427 base: u32,
428) -> Result<(Vec<u8>, Vec<u32>), GpuError> {
429 if mesh.color[3] != 255 {
430 return Err(GpuError::Translucent(mesh.id));
431 }
432 let positions = relative_positions(&mesh.positions, origin, max_error).map_err(|source| {
433 GpuError::Precision {
434 mesh: mesh.id,
435 source,
436 }
437 })?;
438 let color = mesh.color.map(|value| {
440 let value = f32::from(value) / 255.;
441 if value <= 0.04045 {
442 value / 12.92
443 } else {
444 ((value + 0.055) / 1.055).powf(2.4)
445 }
446 });
447 let mut vertices = Vec::with_capacity(positions.len() * VERTEX_BYTES);
448 for position in positions {
449 for value in position.into_iter().chain(color) {
450 vertices.extend_from_slice(&value.to_le_bytes());
451 }
452 }
453 let mut indices = Vec::with_capacity(mesh.triangles.len() * 3);
454 for triangle in &mesh.triangles {
455 for index in triangle {
456 if *index as usize >= mesh.positions.len() {
457 return Err(GpuError::InvalidTriangle(mesh.id));
458 }
459 indices.push(base.checked_add(*index).ok_or(GpuError::BufferLimit)?);
460 }
461 }
462 Ok((vertices, indices))
463}