Skip to main content

qualia_core_db/render/gpu/
mesh_upload.rs

1//! Cold mesh upload, validation, material admission and GPU buffer construction.
2
3use super::*;
4use crate::container_10d::{MaterialRecord, SubmeshRange};
5use crate::render::gpu::materials::create_material_gpu;
6use crate::render::lighting::environment_lighting::{EnvironmentLightingGpu, EnvironmentProbeSet};
7
8const IDENTITY_MAT4: [[f32; 4]; 4] = [
9    [1.0, 0.0, 0.0, 0.0],
10    [0.0, 1.0, 0.0, 0.0],
11    [0.0, 0.0, 1.0, 0.0],
12    [0.0, 0.0, 0.0, 1.0],
13];
14
15impl PortalGpu {
16    /// Update the active mesh's GPU environment contract from raw probe inputs.
17    ///
18    /// `None` is a supported resource state: the bound contract has zero usable probes and the
19    /// shader returns the supplied fallback environment contribution. No CPU lighting evaluation
20    /// is performed here.
21    pub fn set_environment_probes(
22        &mut self,
23        probes: Option<&EnvironmentProbeSet>,
24        fallback_radiance: [f32; 3],
25    ) {
26        let environment = EnvironmentLightingGpu::from_probe_set(probes, fallback_radiance);
27        if let Some(mesh) = self.mesh.as_ref() {
28            mesh.material_gpu
29                .update_environment(&self.queue, &environment);
30        }
31    }
32
33    /// Replace the shared mesh instance source stream. Camera-facing forward and AO passes are
34    /// culled automatically from the active camera; the full source stream remains available to
35    /// shadow cascades so off-camera casters are not dropped. Empty input restores the legacy
36    /// single identity instance. Transparent multi-instance draws are refused until per-instance
37    /// back-to-front ordering is available.
38    pub fn set_mesh_instances(
39        &mut self,
40        records: &[crate::render::instance_culling::GpuInstanceRecord],
41    ) -> Result<(), MeshInstanceUploadError> {
42        self.set_mesh_instances_packed(bytemuck::cast_slice(records))
43    }
44
45    /// Replace instances from the stable byte ABI without requiring caller-pointer alignment.
46    pub fn set_mesh_instances_packed(
47        &mut self,
48        packed_records: &[u8],
49    ) -> Result<(), MeshInstanceUploadError> {
50        let record_size = std::mem::size_of::<crate::render::instance_culling::GpuInstanceRecord>();
51        if packed_records.len() % record_size != 0 {
52            return Err(MeshInstanceUploadError::InvalidTransform { index: 0 });
53        }
54        let record_count = packed_records.len() / record_size;
55        if record_count > 1
56            && self.mesh.as_ref().is_some_and(|mesh| {
57                mesh.material_gpu
58                    .draws
59                    .iter()
60                    .any(|draw| draw.opacity_mode == crate::container_10d::OpacityMode::Blend)
61            })
62        {
63            return Err(MeshInstanceUploadError::TransparentInstancesRequireSortedSubmission);
64        }
65        self.visible_mesh_instances.replace_packed(
66            &self.device,
67            &self.queue,
68            &self.mesh_instance_layout,
69            packed_records,
70        )?;
71        if let Err(error) = self.mesh_instances.replace_packed(
72            &self.device,
73            &self.queue,
74            &self.mesh_instance_layout,
75            packed_records,
76        ) {
77            let previous = bytemuck::cast_slice(&self.mesh_instance_source);
78            let _ = self.visible_mesh_instances.replace_packed(
79                &self.device,
80                &self.queue,
81                &self.mesh_instance_layout,
82                previous,
83            );
84            return Err(error);
85        }
86        self.mesh_instance_source.clear();
87        if packed_records.is_empty() {
88            self.mesh_instance_source.push(
89                crate::render::instance_culling::GpuInstanceRecord::new(IDENTITY_MAT4, 0),
90            );
91        } else {
92            let record_size =
93                std::mem::size_of::<crate::render::instance_culling::GpuInstanceRecord>();
94            for bytes in packed_records.chunks_exact(record_size) {
95                self.mesh_instance_source
96                    .push(bytemuck::pod_read_unaligned(bytes));
97            }
98        }
99        self.last_visibility_key = None;
100        self.shadow_map_dirty = true;
101        self.pick_readback.invalidate(true);
102        self.pick_semantic_result = None;
103        self.source_motion.retire();
104        Ok(())
105    }
106
107    /// Upload an imported triangle mesh (Phase 1.2). `positions` are model-space `f32x3` (the caller
108    /// centres + scales them to the orbit frame); `indices` is a flat triangle list (`tris * 3`).
109    /// Returns the triangle count; clears any prior mesh when empty.
110    pub fn upload_mesh(&mut self, positions: &[[f32; 3]], indices: &[u32]) -> u32 {
111        self.upload_mesh_colored(positions, &[], indices)
112    }
113
114    /// Upload a triangle mesh with per-vertex linear RGBA colours. When `colors` is empty the
115    /// engine's neutral blue-grey material is used; any non-empty slice must match `positions`.
116    pub fn upload_mesh_colored(
117        &mut self,
118        positions: &[[f32; 3]],
119        colors: &[[f32; 4]],
120        indices: &[u32],
121    ) -> u32 {
122        self.upload_mesh_colored_with_normals(positions, colors, None, indices)
123    }
124
125    /// Upload a mesh while preserving a valid authored normal stream when supplied. The generated
126    /// workspace remains resident for later deformation updates, where normals are recomputed from
127    /// the changed geometry.
128    pub fn upload_mesh_colored_with_normals(
129        &mut self,
130        positions: &[[f32; 3]],
131        colors: &[[f32; 4]],
132        authored_normals: Option<&[[f32; 3]]>,
133        indices: &[u32],
134    ) -> u32 {
135        self.upload_mesh_colored_with_frames(positions, colors, authored_normals, None, indices)
136    }
137
138    /// Upload a mesh with optional authored normal and tangent frame streams.
139    pub fn upload_mesh_colored_with_frames(
140        &mut self,
141        positions: &[[f32; 3]],
142        colors: &[[f32; 4]],
143        authored_normals: Option<&[[f32; 3]]>,
144        authored_tangents: Option<&[[f32; 4]]>,
145        indices: &[u32],
146    ) -> u32 {
147        let Ok(index_count) = u32::try_from(indices.len()) else {
148            return 0;
149        };
150        let material = MaterialRecord::legacy_default();
151        let range = SubmeshRange {
152            first_index: 0,
153            index_count,
154            material_id: material.id,
155            semantic_id: 0,
156        };
157        self.upload_mesh_colored_with_frames_and_materials(
158            positions,
159            colors,
160            authored_normals,
161            authored_tangents,
162            indices,
163            &[material],
164            &[range],
165        )
166        .unwrap_or(0)
167    }
168
169    /// Upload a triangle mesh with per-submesh MAT1 shading and validated alpha coverage.
170    pub fn upload_mesh_colored_with_frames_and_materials(
171        &mut self,
172        positions: &[[f32; 3]],
173        colors: &[[f32; 4]],
174        authored_normals: Option<&[[f32; 3]]>,
175        authored_tangents: Option<&[[f32; 4]]>,
176        indices: &[u32],
177        materials: &[MaterialRecord],
178        ranges: &[SubmeshRange],
179    ) -> Result<u32, String> {
180        self.upload_mesh_colored_with_frames_and_materials_and_uv0(
181            positions,
182            colors,
183            authored_normals,
184            authored_tangents,
185            None,
186            indices,
187            materials,
188            ranges,
189        )
190    }
191
192    /// Upload a mesh with optional vertex-aligned glTF TEXCOORD_0 values.
193    pub fn upload_mesh_colored_with_frames_and_materials_and_uv0(
194        &mut self,
195        positions: &[[f32; 3]],
196        colors: &[[f32; 4]],
197        authored_normals: Option<&[[f32; 3]]>,
198        authored_tangents: Option<&[[f32; 4]]>,
199        texture_coordinates_0: Option<&[[f32; 2]]>,
200        indices: &[u32],
201        materials: &[MaterialRecord],
202        ranges: &[SubmeshRange],
203    ) -> Result<u32, String> {
204        self.last_visibility_key = None;
205        if positions.is_empty() || indices.len() < 3 {
206            let generation = self
207                .mesh_generation
208                .checked_add(1)
209                .ok_or_else(|| "mesh generation exhausted".to_string())?;
210            self.mesh = None;
211            self.shadow_map_dirty = true;
212            self.mesh_generation = generation;
213            self.source_motion = Default::default();
214            return Ok(0);
215        }
216        if positions.len() > u32::MAX as usize || indices.len() > u32::MAX as usize {
217            return Err("mesh vertex or index count exceeds u32".to_string());
218        }
219        if !colors.is_empty() && colors.len() != positions.len() {
220            return Err("mesh colour count does not match vertex count".to_string());
221        }
222        if materials.len() > crate::container_10d::MAX_MATERIALS
223            || ranges.len() > materials::MAX_MATERIAL_DRAWS
224        {
225            return Err("mesh material or draw count exceeds renderer limits".to_string());
226        }
227        if self.mesh_instances.count() > 1
228            && materials
229                .iter()
230                .any(|material| material.opacity_mode == crate::container_10d::OpacityMode::Blend)
231        {
232            return Err("transparent meshes require sorted per-instance submission".to_string());
233        }
234        if authored_normals.is_some_and(|normals| {
235            normals.len() != positions.len()
236                || normals.iter().flatten().any(|value| !value.is_finite())
237                || normals.iter().any(|n| {
238                    let length2 = n[0] * n[0] + n[1] * n[1] + n[2] * n[2];
239                    !length2.is_finite() || length2 <= f32::EPSILON
240                })
241        }) {
242            return Err("mesh authored normal stream is invalid".to_string());
243        }
244        if authored_tangents.is_some_and(|tangents| {
245            tangents.len() != positions.len()
246                || tangents.iter().flatten().any(|value| !value.is_finite())
247                || tangents.iter().any(|t| {
248                    let direction2 = t[0] * t[0] + t[1] * t[1] + t[2] * t[2];
249                    !direction2.is_finite()
250                        || direction2 <= f32::EPSILON
251                        || (t[3].abs() - 1.0).abs() > 1e-3
252                })
253        }) {
254            return Err("mesh authored tangent stream is invalid".to_string());
255        }
256        if texture_coordinates_0.is_some_and(|coordinates| {
257            coordinates.len() != positions.len()
258                || coordinates
259                    .iter()
260                    .flatten()
261                    .any(|value| !value.is_finite() || value.abs() > 1_000_000.0)
262        }) {
263            return Err("mesh TEXCOORD_0 stream is invalid".to_string());
264        }
265        let normal_workspace = mesh_normals::MeshNormalWorkspace::new(positions, indices)
266            .map_err(|error| error.to_string())?;
267        let index_count =
268            u32::try_from(indices.len()).map_err(|_| "mesh index count exceeds u32".to_string())?;
269        crate::container_10d::validate_material_bindings(materials, ranges, index_count)
270            .map_err(|error| format!("material ranges are invalid: {error}"))?;
271        let material_bytes = (materials.len() as u64)
272            .checked_mul(materials::MATERIAL_UNIFORM_STRIDE)
273            .and_then(|bytes| {
274                bytes.checked_add(
275                    crate::render::lighting::environment_lighting::ENVIRONMENT_LIGHTING_GPU_SIZE
276                        as u64,
277                )
278            })
279            .ok_or_else(|| "mesh material-uniform size overflow".to_string())?;
280        let position_bytes = (positions.len() as u64).checked_mul(12);
281        let normal_bytes = (positions.len() as u64).checked_mul(12);
282        let tangent_bytes = (positions.len() as u64).checked_mul(16);
283        let color_bytes = (positions.len() as u64).checked_mul(16);
284        let uv_bytes = (positions.len() as u64).checked_mul(8);
285        let index_bytes = (indices.len() as u64).checked_mul(4);
286        let Some(mesh_bytes) = position_bytes
287            .zip(normal_bytes)
288            .zip(tangent_bytes)
289            .zip(color_bytes)
290            .zip(index_bytes)
291            .zip(uv_bytes)
292            .and_then(
293                |(((((positions, normals), tangents), colors), indices), uvs)| {
294                    positions
295                        .checked_add(normals)?
296                        .checked_add(tangents)?
297                        .checked_add(colors)?
298                        .checked_add(indices)?
299                        .checked_add(material_bytes)
300                        .and_then(|bytes| bytes.checked_add(uvs))
301                },
302            )
303        else {
304            return Err("mesh GPU byte size overflow".to_string());
305        };
306        // Reserve the peak before allocating GPU buffers. The old mesh remains
307        // alive until the replacement has been constructed and installed.
308        let Ok(mesh_reservation) = global_vram_ledger()
309            .try_reserve_graphics(crate::gpu_context::VramResourceClass::Geometry, mesh_bytes)
310        else {
311            return Err("mesh GPU geometry reservation refused".to_string());
312        };
313        let material_gpu = create_material_gpu(
314            &self.device,
315            &self.mesh_material_layout,
316            &self.mesh_texture_layout,
317            &self.material_texture_defaults,
318            &self.resident_textures,
319            materials,
320            ranges,
321            positions,
322            indices,
323            index_count,
324        )?;
325        let shadow_draws = material_gpu
326            .draws
327            .iter()
328            .copied()
329            .filter(|draw| {
330                materials[draw.material_index].casts_shadow
331                    && draw.opacity_mode != crate::container_10d::OpacityMode::Blend
332            })
333            .collect();
334        let receives_shadows = materials.iter().any(|material| material.receives_shadow);
335        let default_colors;
336        let colors = if colors.is_empty() {
337            default_colors = vec![[0.50, 0.60, 0.82, 1.0]; positions.len()];
338            default_colors.as_slice()
339        } else {
340            colors
341        };
342
343        let normal_data = authored_normals.unwrap_or_else(|| normal_workspace.normals());
344
345        let generated_tangents;
346        let tangent_data = if let Some(tangents) = authored_tangents {
347            tangents
348        } else if let Some(uv) = texture_coordinates_0 {
349            // UV-aligned normal maps require a real tangent basis rather than
350            // an arbitrary axis derived only from the geometric normal.
351            if positions.len() > 1_048_576 {
352                return Err("tangent authoring scratch exceeds bounded mesh budget".into());
353            }
354            generated_tangents = {
355                let mut frames = vec![[0.0; 4]; positions.len()];
356                let mut scratch = vec![[0.0; 6]; positions.len()];
357                crate::render::mesh_tangent_frames::tangents_from_uvs_into(
358                    positions,
359                    uv,
360                    normal_data,
361                    indices,
362                    &mut frames,
363                    &mut scratch,
364                )
365                .map_err(|e| format!("mesh tangent frames: {e:?}"))?;
366                frames
367            };
368            generated_tangents.as_slice()
369        } else {
370            generated_tangents = normal_data
371                .iter()
372                .copied()
373                .map(default_gpu_tangent)
374                .collect::<Vec<_>>();
375            generated_tangents.as_slice()
376        };
377
378        let default_uvs;
379        let texture_coordinates_0 = if let Some(coordinates) = texture_coordinates_0 {
380            coordinates
381        } else {
382            default_uvs = vec![[0.0, 0.0]; positions.len()];
383            default_uvs.as_slice()
384        };
385
386        let index_count = indices.len() as u32;
387        let generation = self
388            .mesh_generation
389            .checked_add(1)
390            .ok_or_else(|| "mesh generation exhausted".to_string())?;
391        let buffers = etalon_render::mesh::MeshBuffers::upload(
392            &self.device,
393            positions,
394            colors,
395            normal_data,
396            tangent_data,
397            texture_coordinates_0,
398            indices,
399            mesh_reservation,
400        )?;
401        self.pick_readback.invalidate(false);
402        self.pick_semantic_result = None;
403        self.mesh = Some(MeshGpu {
404            buffers,
405            material_gpu,
406            shadow_draws,
407            receives_shadows,
408            cpu_positions: positions.to_vec(),
409            cpu_indices: indices.to_vec(),
410            normal_workspace,
411        });
412        self.mesh_base_aabb = Aabb::from_points(positions); // for Phase 2 admission
413        self.last_visibility_key = None;
414        self.shadow_map_dirty = true;
415        self.last_admitted = Motor::identity();
416        self.last_refused = false;
417        self.mesh_generation = generation;
418        self.source_motion = Default::default();
419        Ok(index_count / 3)
420    }
421
422    /// Replace a span of mesh positions. The buffer is `COPY_DST`. Used so a
423    /// part can change over time without uploading the whole scene again.
424    pub fn write_mesh_vertices(&mut self, start: u32, positions: &[[f32; 3]]) {
425        let Some(mesh) = self.mesh.as_mut() else {
426            return;
427        };
428        let start_us = start as usize;
429        let Some(end) = start_us.checked_add(positions.len()) else {
430            return;
431        };
432        if positions.is_empty()
433            || end > mesh.vertex_count as usize
434            || positions.iter().flatten().any(|value| !value.is_finite())
435        {
436            return;
437        }
438        if mesh
439            .normal_workspace
440            .validate_position_span(mesh.cpu_positions.len(), start_us, end)
441            .is_err()
442        {
443            return;
444        }
445        mesh.cpu_positions[start_us..end].copy_from_slice(positions);
446        materials::update_draw_bounds(
447            &mut mesh.material_gpu.draws,
448            &mesh.cpu_positions,
449            &mesh.cpu_indices,
450        );
451        materials::update_draw_bounds(
452            &mut mesh.shadow_draws,
453            &mesh.cpu_positions,
454            &mesh.cpu_indices,
455        );
456        self.mesh_base_aabb = Aabb::from_points(&mesh.cpu_positions);
457        self.last_visibility_key = None;
458        self.shadow_map_dirty = true;
459        mesh.normal_workspace
460            .update_positions_prevalidated(&mesh.cpu_positions, start_us, end);
461        self.pick_readback.invalidate(true);
462        self.pick_semantic_result = None;
463        self.source_motion.retire();
464        self.queue.write_buffer(
465            &mesh.vertex_buf,
466            (start_us * 12) as u64,
467            bytemuck::cast_slice(positions),
468        );
469        let (dirty, normals) = mesh.normal_workspace.sorted_dirty_vertices_and_normals();
470        if let Some(&first) = dirty.first() {
471            let mut run_start = first as usize;
472            let mut run_end = run_start + 1;
473            for &vertex in &dirty[1..] {
474                let vertex = vertex as usize;
475                if vertex == run_end {
476                    run_end += 1;
477                    continue;
478                }
479                self.queue.write_buffer(
480                    &mesh.buffers.normal_buf,
481                    (run_start * 12) as u64,
482                    bytemuck::cast_slice(&normals[run_start..run_end]),
483                );
484                run_start = vertex;
485                run_end = vertex + 1;
486            }
487            self.queue.write_buffer(
488                &mesh.buffers.normal_buf,
489                (run_start * 12) as u64,
490                bytemuck::cast_slice(&normals[run_start..run_end]),
491            );
492        }
493    }
494
495    /// Whether a mesh surface is resident.
496    pub fn has_mesh(&self) -> bool {
497        self.mesh.is_some()
498    }
499}