1pub use crate::morph_target::MorphTarget;
2use crate::{BuildError, MaterialId, NodeId, SkinId, TextureId, Transform};
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum PrimitiveTopology {
11 Points,
13 Lines,
15 LineStrip,
17 Triangles,
19}
20
21#[derive(Debug, Clone, PartialEq)]
27pub struct SkinningSet {
28 joints: Vec<[u16; 4]>,
29 weights: Vec<[f32; 4]>,
30}
31
32impl SkinningSet {
33 pub fn new(joints: Vec<[u16; 4]>, weights: Vec<[f32; 4]>) -> Self {
38 Self { joints, weights }
39 }
40
41 pub fn joints(&self) -> &[[u16; 4]] {
43 &self.joints
44 }
45
46 pub fn weights(&self) -> &[[f32; 4]] {
48 &self.weights
49 }
50}
51
52#[derive(Debug, Clone)]
59pub struct RenderPrimitive {
60 node_index: u32,
63 world_transform: Transform,
66 positions: Vec<[f32; 3]>,
68 normals: Vec<[f32; 3]>,
70 indices: Vec<u32>,
72 skinning_sets: Vec<SkinningSet>,
74 morph_targets: Vec<MorphTarget>,
76 texcoord_sets: Vec<Vec<[f32; 2]>>,
78 tangents: Vec<[f32; 4]>,
80 colors: Vec<[f32; 4]>,
82 texture_index: Option<usize>,
85 material_index: Option<usize>,
88 topology: PrimitiveTopology,
90 morph_weights: Vec<f32>,
93 base_morph_weights: Vec<f32>,
97 flat_normals: bool,
101 skin_index: Option<usize>,
102 base_color_texcoord: u32,
103}
104
105#[derive(Debug, Clone)]
112pub struct MorphedVertices {
113 pub positions: Vec<[f32; 3]>,
115 pub normals: Vec<[f32; 3]>,
117 pub tangents: Vec<[f32; 4]>,
119}
120
121#[derive(Debug, Clone)]
127pub struct RenderPrimitiveBuilder {
128 node_id: NodeId,
129 world_transform: Transform,
130 positions: Vec<[f32; 3]>,
131 normals: Option<Vec<[f32; 3]>>,
132 indices: Vec<u32>,
133 skinning_sets: Vec<SkinningSet>,
134 morph_targets: Vec<MorphTarget>,
135 texcoord_sets: Vec<Vec<[f32; 2]>>,
136 tangents: Option<Vec<[f32; 4]>>,
137 colors: Option<Vec<[f32; 4]>>,
138 texture: Option<(TextureId, u32)>,
139 material_id: Option<MaterialId>,
140 topology: PrimitiveTopology,
141 morph_weights: Option<Vec<f32>>,
142 skin_id: Option<SkinId>,
143}
144
145impl RenderPrimitiveBuilder {
146 pub fn new(node_id: NodeId, positions: Vec<[f32; 3]>, indices: Vec<u32>) -> Self {
151 Self {
152 node_id,
153 world_transform: Transform::IDENTITY,
154 positions,
155 normals: None,
156 indices,
157 skinning_sets: Vec::new(),
158 morph_targets: Vec::new(),
159 texcoord_sets: Vec::new(),
160 tangents: None,
161 colors: None,
162 texture: None,
163 material_id: None,
164 topology: PrimitiveTopology::Triangles,
165 morph_weights: None,
166 skin_id: None,
167 }
168 }
169
170 pub const fn with_world_transform(mut self, transform: Transform) -> Self {
175 self.world_transform = transform;
176 self
177 }
178
179 pub fn with_normals(mut self, normals: Vec<[f32; 3]>) -> Self {
181 self.normals = Some(normals);
182 self
183 }
184
185 pub fn with_skinning(mut self, joints: Vec<[u16; 4]>, weights: Vec<[f32; 4]>) -> Self {
187 self.skinning_sets = vec![SkinningSet::new(joints, weights)];
188 self
189 }
190
191 pub fn with_skinning_sets(mut self, skinning_sets: Vec<SkinningSet>) -> Self {
193 self.skinning_sets = skinning_sets;
194 self
195 }
196
197 pub const fn with_skin(mut self, skin_id: SkinId) -> Self {
199 self.skin_id = Some(skin_id);
200 self
201 }
202
203 pub fn with_morph_target(
205 mut self,
206 position_deltas: Vec<[f32; 3]>,
207 normal_deltas: Option<Vec<[f32; 3]>>,
208 tangent_deltas: Option<Vec<[f32; 3]>>,
209 ) -> Self {
210 self.morph_targets.push(MorphTarget::new(
211 position_deltas,
212 normal_deltas,
213 tangent_deltas,
214 ));
215 self
216 }
217
218 pub fn with_morph_targets(mut self, morph_targets: Vec<MorphTarget>) -> Self {
220 self.morph_targets = morph_targets;
221 self
222 }
223
224 pub fn with_morph_weights(mut self, morph_weights: Vec<f32>) -> Self {
226 self.morph_weights = Some(morph_weights);
227 self
228 }
229
230 pub fn with_texcoords(mut self, texcoords: Vec<[f32; 2]>) -> Self {
232 if self.texcoord_sets.is_empty() {
233 self.texcoord_sets.push(texcoords);
234 } else {
235 self.texcoord_sets[0] = texcoords;
236 }
237 self
238 }
239
240 pub fn with_secondary_texcoords(mut self, texcoords: Vec<[f32; 2]>) -> Self {
242 while self.texcoord_sets.len() < 2 {
243 self.texcoord_sets.push(Vec::new());
244 }
245 self.texcoord_sets[1] = texcoords;
246 self
247 }
248
249 pub fn with_texcoord_sets(mut self, texcoord_sets: Vec<Vec<[f32; 2]>>) -> Self {
251 self.texcoord_sets = texcoord_sets;
252 self
253 }
254
255 pub fn with_tangents(mut self, tangents: Vec<[f32; 4]>) -> Self {
257 self.tangents = Some(tangents);
258 self
259 }
260
261 pub fn with_colors(mut self, colors: Vec<[f32; 4]>) -> Self {
263 self.colors = Some(colors);
264 self
265 }
266
267 pub const fn with_material(mut self, material_id: MaterialId) -> Self {
269 self.material_id = Some(material_id);
270 self
271 }
272
273 pub const fn with_base_color_texture(mut self, texture_id: TextureId, tex_coord: u32) -> Self {
278 self.texture = Some((texture_id, tex_coord));
279 self
280 }
281
282 pub const fn with_topology(mut self, topology: PrimitiveTopology) -> Self {
284 self.topology = topology;
285 self
286 }
287
288 pub fn build(self) -> Result<RenderPrimitive, BuildError> {
293 self.validate()?;
294
295 let Self {
296 node_id,
297 world_transform,
298 positions,
299 normals,
300 indices,
301 skinning_sets,
302 morph_targets,
303 texcoord_sets,
304 tangents,
305 colors,
306 texture,
307 material_id,
308 topology,
309 morph_weights,
310 skin_id,
311 } = self;
312 let vertex_count = positions.len();
313 let has_normals = normals.is_some();
314 let vertex = VertexBuffers {
315 positions,
316 texcoord_sets,
317 colors: colors.unwrap_or_else(|| vec![[1.0, 1.0, 1.0, 1.0]; vertex_count]),
318 skinning_sets,
319 morph_targets,
320 };
321 let (vertex, normals, indices, flat_normals) =
322 resolve_normals(vertex, indices, normals, topology);
323 let tangents = resolve_tangents(
324 tangents,
325 has_normals,
326 None,
327 &vertex,
328 &normals,
329 &indices,
330 topology,
331 );
332 let morph_weights = morph_weights.unwrap_or_else(|| vec![0.0; vertex.morph_targets.len()]);
333 let (texture_index, base_color_texcoord) = texture
334 .map(|(texture_id, tex_coord)| (Some(texture_id.index()), tex_coord))
335 .unwrap_or((None, 0));
336 let skin_index = skin_id.map(SkinId::index);
337
338 Ok(RenderPrimitive::new_with_sets(
339 node_id.index() as u32,
340 if skin_index.is_some() {
341 Transform::IDENTITY
342 } else {
343 world_transform
344 },
345 vertex.positions,
346 normals,
347 indices,
348 vertex.skinning_sets,
349 vertex.morph_targets,
350 vertex.texcoord_sets,
351 tangents,
352 vertex.colors,
353 texture_index,
354 material_id.map(MaterialId::index),
355 topology,
356 morph_weights,
357 flat_normals,
358 skin_index,
359 base_color_texcoord,
360 ))
361 }
362
363 fn validate(&self) -> Result<(), BuildError> {
364 let invalid = |message: &str| {
365 BuildError::InvalidAsset(format!("invalid render primitive: {message}"))
366 };
367 let vertex_count = self.positions.len();
368 if self
369 .positions
370 .iter()
371 .flatten()
372 .any(|component| !component.is_finite())
373 {
374 return Err(invalid("positions must be finite"));
375 }
376 if self
377 .world_transform
378 .matrix()
379 .iter()
380 .flatten()
381 .any(|component| !component.is_finite())
382 {
383 return Err(invalid("the world transform must be finite"));
384 }
385 if self
386 .indices
387 .iter()
388 .any(|index| *index as usize >= vertex_count)
389 {
390 return Err(invalid("an index is outside the position buffer"));
391 }
392 match self.topology {
393 PrimitiveTopology::Triangles if !self.indices.len().is_multiple_of(3) => {
394 return Err(invalid("triangle indices must be a multiple of three"));
395 }
396 PrimitiveTopology::Lines if !self.indices.len().is_multiple_of(2) => {
397 return Err(invalid("line indices must be a multiple of two"));
398 }
399 _ => {}
400 }
401
402 for (name, length) in [
403 ("normal", self.normals.as_ref().map(Vec::len)),
404 ("tangent", self.tangents.as_ref().map(Vec::len)),
405 ("color", self.colors.as_ref().map(Vec::len)),
406 ] {
407 if length.is_some_and(|length| length != vertex_count) {
408 return Err(invalid(&format!(
409 "the {name} buffer must contain one value per position"
410 )));
411 }
412 }
413 for (set, texcoords) in self.texcoord_sets.iter().enumerate() {
414 if texcoords.len() != vertex_count {
415 return Err(invalid(&format!(
416 "UV set {set} must contain one value per position"
417 )));
418 }
419 }
420 for (set, skinning) in self.skinning_sets.iter().enumerate() {
421 if skinning.joints.len() != vertex_count || skinning.weights.len() != vertex_count {
422 return Err(invalid(&format!(
423 "skinning set {set} must contain one joint and weight value per position"
424 )));
425 }
426 }
427
428 let all_finite = self
429 .normals
430 .iter()
431 .flatten()
432 .flatten()
433 .chain(
434 self.skinning_sets
435 .iter()
436 .flat_map(|set| set.weights.iter().flatten()),
437 )
438 .chain(self.texcoord_sets.iter().flatten().flatten())
439 .chain(self.tangents.iter().flatten().flatten())
440 .chain(self.colors.iter().flatten().flatten())
441 .all(|component| component.is_finite());
442 if !all_finite {
443 return Err(invalid("vertex attributes must be finite"));
444 }
445 if self
446 .skinning_sets
447 .iter()
448 .any(|set| set.weights.iter().flatten().any(|weight| *weight < 0.0))
449 {
450 return Err(invalid("skinning weights must be non-negative"));
451 }
452 if (0..vertex_count).any(|vertex| {
453 let sum: f32 = self
454 .skinning_sets
455 .iter()
456 .flat_map(|set| set.weights[vertex])
457 .sum();
458 sum != 0.0 && (sum - 1.0).abs() > 1.0e-3
459 }) {
460 return Err(invalid(
461 "non-zero skinning weights must sum to one per vertex",
462 ));
463 }
464 for vertex in 0..vertex_count {
465 let mut weighted_joints = Vec::new();
466 for set in &self.skinning_sets {
467 for (&joint, &weight) in set.joints[vertex].iter().zip(&set.weights[vertex]) {
468 if weight > 0.0 && weighted_joints.contains(&joint) {
469 return Err(invalid(
470 "a joint must not have more than one non-zero weight per vertex",
471 ));
472 }
473 if weight > 0.0 {
474 weighted_joints.push(joint);
475 }
476 }
477 }
478 }
479
480 for target in &self.morph_targets {
481 if target.position_deltas().len() != vertex_count
482 || target
483 .normal_deltas()
484 .is_some_and(|values| values.len() != vertex_count)
485 || target
486 .tangent_deltas()
487 .is_some_and(|values| values.len() != vertex_count)
488 {
489 return Err(invalid(
490 "each morph target buffer must contain one value per position",
491 ));
492 }
493 if target
494 .position_deltas()
495 .iter()
496 .flatten()
497 .chain(target.normal_deltas().into_iter().flatten().flatten())
498 .chain(target.tangent_deltas().into_iter().flatten().flatten())
499 .any(|component| !component.is_finite())
500 {
501 return Err(invalid("morph target deltas must be finite"));
502 }
503 }
504 if self
505 .morph_weights
506 .as_ref()
507 .is_some_and(|weights| weights.len() != self.morph_targets.len())
508 {
509 return Err(invalid("there must be one weight per morph target"));
510 }
511 if self
512 .morph_weights
513 .iter()
514 .flatten()
515 .any(|weight| !weight.is_finite())
516 {
517 return Err(invalid("morph weights must be finite"));
518 }
519 Ok(())
520 }
521}
522
523impl RenderPrimitive {
524 pub fn builder(
526 node_id: NodeId,
527 positions: Vec<[f32; 3]>,
528 indices: Vec<u32>,
529 ) -> RenderPrimitiveBuilder {
530 RenderPrimitiveBuilder::new(node_id, positions, indices)
531 }
532
533 #[allow(clippy::too_many_arguments)]
534 pub(crate) fn new_with_sets(
535 node_index: u32,
536 world_transform: Transform,
537 positions: Vec<[f32; 3]>,
538 normals: Vec<[f32; 3]>,
539 indices: Vec<u32>,
540 skinning_sets: Vec<SkinningSet>,
541 morph_targets: Vec<MorphTarget>,
542 texcoord_sets: Vec<Vec<[f32; 2]>>,
543 tangents: Vec<[f32; 4]>,
544 colors: Vec<[f32; 4]>,
545 texture_index: Option<usize>,
546 material_index: Option<usize>,
547 topology: PrimitiveTopology,
548 morph_weights: Vec<f32>,
549 flat_normals: bool,
550 skin_index: Option<usize>,
551 base_color_texcoord: u32,
552 ) -> Self {
553 let base_morph_weights = morph_weights.clone();
554 Self {
555 node_index,
556 world_transform,
557 positions,
558 normals,
559 indices,
560 skinning_sets,
561 morph_targets,
562 texcoord_sets,
563 tangents,
564 colors,
565 texture_index,
566 material_index,
567 topology,
568 morph_weights,
569 base_morph_weights,
570 flat_normals,
571 skin_index,
572 base_color_texcoord,
573 }
574 }
575
576 #[cfg(test)]
579 #[allow(clippy::too_many_arguments)]
580 pub(crate) fn new(
581 node_index: u32,
582 world_transform: Transform,
583 positions: Vec<[f32; 3]>,
584 normals: Vec<[f32; 3]>,
585 indices: Vec<u32>,
586 joints: Vec<[u16; 4]>,
587 weights: Vec<[f32; 4]>,
588 morph_targets: Vec<MorphTarget>,
589 texcoords: Vec<[f32; 2]>,
590 tangents: Vec<[f32; 4]>,
591 colors: Vec<[f32; 4]>,
592 secondary_texcoords: Vec<[f32; 2]>,
593 texture_index: Option<usize>,
594 material_index: Option<usize>,
595 topology: PrimitiveTopology,
596 morph_weights: Vec<f32>,
597 flat_normals: bool,
598 skin_index: Option<usize>,
599 base_color_texcoord: u32,
600 ) -> Self {
601 Self::new_with_sets(
602 node_index,
603 world_transform,
604 positions,
605 normals,
606 indices,
607 vec![SkinningSet::new(joints, weights)],
608 morph_targets,
609 vec![texcoords, secondary_texcoords],
610 tangents,
611 colors,
612 texture_index,
613 material_index,
614 topology,
615 morph_weights,
616 flat_normals,
617 skin_index,
618 base_color_texcoord,
619 )
620 }
621
622 pub fn node_index(&self) -> u32 {
624 self.node_index
625 }
626
627 pub fn node_id(&self) -> NodeId {
629 NodeId::from_index(self.node_index as usize)
630 }
631
632 pub fn world_transform(&self) -> &Transform {
638 &self.world_transform
639 }
640
641 pub fn positions(&self) -> &[[f32; 3]] {
643 &self.positions
644 }
645
646 pub fn normals(&self) -> &[[f32; 3]] {
648 &self.normals
649 }
650
651 pub fn indices(&self) -> &[u32] {
653 &self.indices
654 }
655
656 pub fn joints(&self) -> &[[u16; 4]] {
658 self.skinning_sets
659 .first()
660 .map(SkinningSet::joints)
661 .unwrap_or(&[])
662 }
663
664 pub fn weights(&self) -> &[[f32; 4]] {
666 self.skinning_sets
667 .first()
668 .map(SkinningSet::weights)
669 .unwrap_or(&[])
670 }
671
672 pub fn skinning_sets(&self) -> &[SkinningSet] {
674 &self.skinning_sets
675 }
676
677 pub fn morph_targets(&self) -> &[MorphTarget] {
679 &self.morph_targets
680 }
681
682 pub fn texcoords(&self) -> &[[f32; 2]] {
684 self.texcoord_set(0).unwrap_or(&[])
685 }
686
687 pub fn texcoord_sets(&self) -> &[Vec<[f32; 2]>] {
689 &self.texcoord_sets
690 }
691
692 pub fn texcoord_set(&self, set: u32) -> Option<&[[f32; 2]]> {
694 self.texcoord_sets.get(set as usize).map(Vec::as_slice)
695 }
696
697 pub fn tangents(&self) -> &[[f32; 4]] {
699 &self.tangents
700 }
701
702 pub fn colors(&self) -> &[[f32; 4]] {
704 &self.colors
705 }
706
707 pub fn secondary_texcoords(&self) -> &[[f32; 2]] {
709 self.texcoord_set(1).unwrap_or(&[])
710 }
711
712 pub fn texture_index(&self) -> Option<usize> {
714 self.texture_index
715 }
716
717 pub fn texture_id(&self) -> Option<TextureId> {
719 self.texture_index.map(TextureId::from_index)
720 }
721
722 pub fn material_index(&self) -> Option<usize> {
724 self.material_index
725 }
726
727 pub fn material_id(&self) -> Option<MaterialId> {
729 self.material_index.map(MaterialId::from_index)
730 }
731
732 pub fn topology(&self) -> PrimitiveTopology {
734 self.topology
735 }
736
737 pub fn morph_weights(&self) -> &[f32] {
739 &self.morph_weights
740 }
741
742 pub fn base_morph_weights(&self) -> &[f32] {
746 &self.base_morph_weights
747 }
748
749 pub fn set_morph_weights(&mut self, weights: &[f32]) {
753 self.morph_weights.clear();
754 self.morph_weights
755 .extend(weights.iter().copied().take(self.morph_targets.len()));
756 self.morph_weights.resize(self.morph_targets.len(), 0.0);
757 }
758
759 pub fn apply_morph_update(&mut self, target_index: u32, weight: f32) {
765 if target_index as usize >= self.morph_targets.len() {
766 return;
767 }
768 self.morph_weights.resize(self.morph_targets.len(), 0.0);
769 self.morph_weights[target_index as usize] = weight.clamp(0.0, 1.0);
770 }
771
772 pub fn reset_morph_weights(&mut self) {
776 self.morph_weights.clear();
777 self.morph_weights
778 .extend(self.base_morph_weights.iter().copied());
779 self.morph_weights.resize(self.morph_targets.len(), 0.0);
780 }
781
782 pub fn morphed_vertices(&self) -> MorphedVertices {
790 self.morphed_vertices_with_weights(&self.morph_weights)
791 }
792
793 pub fn morphed_vertices_with_weights(&self, morph_weights: &[f32]) -> MorphedVertices {
796 let mut positions = self.positions.clone();
797 let mut normals = self.normals.clone();
798 let mut tangents = self.tangents.clone();
799
800 for (weight, target) in morph_weights.iter().zip(&self.morph_targets) {
801 let weight = *weight;
802 if weight == 0.0 {
803 continue;
804 }
805 for (position, delta) in positions.iter_mut().zip(target.position_deltas()) {
806 *position = [
807 position[0] + weight * delta[0],
808 position[1] + weight * delta[1],
809 position[2] + weight * delta[2],
810 ];
811 }
812 if let Some(normal_deltas) = target.normal_deltas() {
813 for (normal, delta) in normals.iter_mut().zip(normal_deltas) {
814 *normal = [
815 normal[0] + weight * delta[0],
816 normal[1] + weight * delta[1],
817 normal[2] + weight * delta[2],
818 ];
819 }
820 }
821 if let Some(tangent_deltas) = target.tangent_deltas() {
822 for (tangent, delta) in tangents.iter_mut().zip(tangent_deltas) {
823 tangent[0] += weight * delta[0];
824 tangent[1] += weight * delta[1];
825 tangent[2] += weight * delta[2];
826 }
827 }
828 }
829
830 if self.flat_normals {
831 normals = compute_flat_normals(&positions, &self.indices);
834 } else {
835 for normal in &mut normals {
836 *normal = glam::Vec3::from_array(*normal)
837 .normalize_or_zero()
838 .to_array();
839 }
840 }
841
842 for tangent in &mut tangents {
843 let xyz = glam::Vec3::from_array([tangent[0], tangent[1], tangent[2]]);
844 let normalized = xyz.normalize_or_zero();
845 tangent[0] = normalized.x;
846 tangent[1] = normalized.y;
847 tangent[2] = normalized.z;
848 }
849
850 MorphedVertices {
851 positions,
852 normals,
853 tangents,
854 }
855 }
856
857 pub fn skin_index(&self) -> Option<usize> {
859 self.skin_index
860 }
861
862 pub fn skin_id(&self) -> Option<SkinId> {
864 self.skin_index.map(SkinId::from_index)
865 }
866
867 pub fn base_color_texcoord(&self) -> u32 {
869 self.base_color_texcoord
870 }
871}
872
873pub(crate) fn load_primitives(
878 document: &gltf::Document,
879 buffers: &[gltf::buffer::Data],
880) -> Result<Vec<RenderPrimitive>, crate::LoadError> {
881 let mut primitives = Vec::new();
882
883 let Some(scene) = document
884 .default_scene()
885 .or_else(|| document.scenes().next())
886 else {
887 return Ok(primitives);
888 };
889
890 let mut stack = scene
893 .nodes()
894 .collect::<Vec<_>>()
895 .into_iter()
896 .rev()
897 .map(|node| (node, Transform::IDENTITY))
898 .collect::<Vec<_>>();
899 while let Some((node, parent_transform)) = stack.pop() {
900 let world_transform =
901 parent_transform.multiply(Transform::from_matrix(node.transform().matrix()));
902
903 if let Some(mesh) = node.mesh() {
904 for primitive in mesh.primitives() {
905 load_primitive(
906 &node,
907 &mesh,
908 primitive,
909 world_transform,
910 buffers,
911 &mut primitives,
912 )?;
913 }
914 }
915
916 let children = node.children().collect::<Vec<_>>();
917 stack.extend(
918 children
919 .into_iter()
920 .rev()
921 .map(|child| (child, world_transform)),
922 );
923 }
924
925 Ok(primitives)
926}
927
928pub(crate) fn validate_referenced_primitive_positions(
931 root: &gltf::json::Root,
932) -> Result<(), crate::LoadError> {
933 for (node_index, node) in root.nodes.iter().enumerate() {
934 let Some(mesh_index) = node.mesh.map(|index| index.value()) else {
935 continue;
936 };
937 let Some(mesh) = root.meshes.get(mesh_index) else {
940 continue;
941 };
942 for (primitive_index, primitive) in mesh.primitives.iter().enumerate() {
943 let has_positions = primitive.attributes.keys().any(|semantic| {
944 matches!(
945 semantic,
946 gltf::json::validation::Checked::Valid(gltf::json::mesh::Semantic::Positions)
947 )
948 });
949 if !has_positions {
950 return Err(missing_position_error(
951 node_index,
952 mesh_index,
953 primitive_index,
954 ));
955 }
956 }
957 }
958 Ok(())
959}
960
961fn missing_position_error(
962 node_index: usize,
963 mesh_index: usize,
964 primitive_index: usize,
965) -> crate::LoadError {
966 crate::LoadError::InvalidVrm(format!(
967 "node {} references mesh {} primitive {}, which is missing the mandatory POSITION attribute",
968 node_index, mesh_index, primitive_index
969 ))
970}
971
972fn load_primitive(
974 node: &gltf::Node<'_>,
975 mesh: &gltf::Mesh<'_>,
976 primitive: gltf::Primitive<'_>,
977 world_transform: Transform,
978 buffers: &[gltf::buffer::Data],
979 primitives: &mut Vec<RenderPrimitive>,
980) -> Result<(), crate::LoadError> {
981 let reader = primitive.reader(|buffer| Some(buffers[buffer.index()].0.as_slice()));
984
985 let Some(positions) = reader.read_positions() else {
988 return Err(missing_position_error(
989 node.index(),
990 mesh.index(),
991 primitive.index(),
992 ));
993 };
994 let positions: Vec<[f32; 3]> = positions.collect();
995 let base_vertex_count = positions.len();
996 validate_f32_attribute(
997 "POSITION",
998 &positions,
999 base_vertex_count,
1000 mesh.index(),
1001 primitive.index(),
1002 )?;
1003
1004 let source_indices: Vec<u32> = match reader.read_indices() {
1007 Some(indices) => indices.into_u32().collect(),
1008 None => (0..base_vertex_count as u32).collect(),
1009 };
1010 if let Some(index) = source_indices
1011 .iter()
1012 .copied()
1013 .find(|&index| index as usize >= base_vertex_count)
1014 {
1015 return Err(crate::LoadError::InvalidVrm(format!(
1016 "mesh {} primitive {} has element index {index} outside its {base_vertex_count}-element POSITION buffer",
1017 mesh.index(),
1018 primitive.index()
1019 )));
1020 }
1021 let (topology, indices) = normalize_topology(primitive.mode(), source_indices);
1022
1023 let supplied_normals = reader
1026 .read_normals()
1027 .map(|normals| normals.collect::<Vec<_>>());
1028 let stored_tangents = reader
1029 .read_tangents()
1030 .map(|tangents| tangents.collect::<Vec<_>>());
1031 if let Some(normals) = supplied_normals.as_deref() {
1032 validate_f32_attribute(
1033 "NORMAL",
1034 normals,
1035 base_vertex_count,
1036 mesh.index(),
1037 primitive.index(),
1038 )?;
1039 }
1040 if let Some(tangents) = stored_tangents.as_deref() {
1041 validate_f32_attribute(
1042 "TANGENT",
1043 tangents,
1044 base_vertex_count,
1045 mesh.index(),
1046 primitive.index(),
1047 )?;
1048 }
1049 let has_normals = supplied_normals.is_some();
1050 let IndexedAttributeSets {
1051 texcoords: texcoord_indices,
1052 joints: joint_indices,
1053 weights: weight_indices,
1054 } = indexed_attribute_sets(&primitive, base_vertex_count)?;
1055 if joint_indices != weight_indices {
1056 return Err(crate::LoadError::InvalidVrm(format!(
1057 "mesh {} primitive {} must contain equal JOINTS_n and WEIGHTS_n sets",
1058 mesh.index(),
1059 primitive.index()
1060 )));
1061 }
1062
1063 let texcoord_sets = texcoord_indices
1064 .iter()
1065 .map(|&set| {
1066 read_texcoords(reader.read_tex_coords(set), base_vertex_count).ok_or_else(|| {
1067 crate::LoadError::InvalidVrm(format!(
1068 "mesh {} primitive {} could not decode TEXCOORD_{set}",
1069 mesh.index(),
1070 primitive.index()
1071 ))
1072 })
1073 })
1074 .collect::<Result<Vec<_>, _>>()?;
1075 for (set, texcoords) in texcoord_sets.iter().enumerate() {
1076 validate_f32_attribute(
1077 &format!("TEXCOORD_{set}"),
1078 texcoords,
1079 base_vertex_count,
1080 mesh.index(),
1081 primitive.index(),
1082 )?;
1083 }
1084 let mut skinning_sets = joint_indices
1085 .iter()
1086 .map(|&set| {
1087 let joints = read_joints(reader.read_joints(set), base_vertex_count).ok_or_else(|| {
1088 crate::LoadError::InvalidVrm(format!(
1089 "mesh {} primitive {} could not decode JOINTS_{set}",
1090 mesh.index(),
1091 primitive.index()
1092 ))
1093 })?;
1094 let weights =
1095 read_weights(reader.read_weights(set), base_vertex_count).ok_or_else(|| {
1096 crate::LoadError::InvalidVrm(format!(
1097 "mesh {} primitive {} could not decode WEIGHTS_{set}",
1098 mesh.index(),
1099 primitive.index()
1100 ))
1101 })?;
1102 if joints.len() != base_vertex_count || weights.len() != base_vertex_count {
1103 return Err(crate::LoadError::InvalidVrm(format!(
1104 "mesh {} primitive {} skinning set {set} does not contain one value per position",
1105 mesh.index(),
1106 primitive.index()
1107 )));
1108 }
1109 Ok(SkinningSet::new(joints, weights))
1110 })
1111 .collect::<Result<Vec<_>, crate::LoadError>>()?;
1112 let skin = node
1113 .skin()
1114 .map(|skin| (skin.index(), skin.joints().count()));
1115 validate_and_normalize_skinning_sets(
1116 &mut skinning_sets,
1117 skin,
1118 mesh.index(),
1119 primitive.index(),
1120 base_vertex_count,
1121 )?;
1122
1123 let colors = read_colors(reader.read_colors(0), base_vertex_count);
1124 validate_f32_attribute(
1125 "COLOR_0",
1126 &colors,
1127 base_vertex_count,
1128 mesh.index(),
1129 primitive.index(),
1130 )?;
1131 let morph_targets = read_morph_targets(&reader, base_vertex_count);
1132 validate_morph_targets(
1133 &morph_targets,
1134 base_vertex_count,
1135 mesh.index(),
1136 primitive.index(),
1137 )?;
1138
1139 let vertex = VertexBuffers {
1142 positions,
1143 texcoord_sets,
1144 colors,
1145 skinning_sets,
1146 morph_targets,
1147 };
1148
1149 let material = primitive.material();
1152 let (texture_index, base_color_texcoord) = base_color_texture(&material);
1153 let material_index = material.index();
1154 let normal_texture_texcoord = normal_texture_texcoord(&material);
1155
1156 let (vertex, normals, indices, flat_normals) =
1157 resolve_normals(vertex, indices, supplied_normals, topology);
1158
1159 let tangents = resolve_loaded_tangents(
1160 stored_tangents,
1161 has_normals,
1162 normal_texture_texcoord,
1163 &vertex,
1164 &normals,
1165 &indices,
1166 topology,
1167 );
1168
1169 let morph_weights = resolve_morph_weights(
1172 node.weights(),
1173 mesh.weights(),
1174 vertex.morph_targets.len(),
1175 node.index(),
1176 mesh.index(),
1177 primitive.index(),
1178 )?;
1179
1180 let skin_index = node.skin().map(|skin| skin.index());
1184 primitives.push(RenderPrimitive::new_with_sets(
1185 node.index() as u32,
1186 if skin_index.is_some() {
1187 Transform::IDENTITY
1188 } else {
1189 world_transform
1190 },
1191 vertex.positions,
1192 normals,
1193 indices,
1194 vertex.skinning_sets,
1195 vertex.morph_targets,
1196 vertex.texcoord_sets,
1197 tangents,
1198 vertex.colors,
1199 texture_index,
1200 material_index,
1201 topology,
1202 morph_weights,
1203 flat_normals,
1204 skin_index,
1205 base_color_texcoord,
1206 ));
1207 Ok(())
1208}
1209
1210fn resolve_morph_weights(
1213 node_weights: Option<&[f32]>,
1214 mesh_weights: Option<&[f32]>,
1215 target_count: usize,
1216 node_index: usize,
1217 mesh_index: usize,
1218 primitive_index: usize,
1219) -> Result<Vec<f32>, crate::LoadError> {
1220 let Some((source, weights)) = node_weights
1221 .map(|weights| ("node", weights))
1222 .or_else(|| mesh_weights.map(|weights| ("mesh", weights)))
1223 else {
1224 return Ok(vec![0.0; target_count]);
1225 };
1226
1227 if weights.len() != target_count {
1228 return Err(crate::LoadError::InvalidVrm(format!(
1229 "node {node_index} mesh {mesh_index} primitive {primitive_index} has {source} morph weights with {} weights for {target_count} morph target{}",
1230 weights.len(),
1231 if target_count == 1 { "" } else { "s" }
1232 )));
1233 }
1234 if weights.iter().any(|weight| !weight.is_finite()) {
1235 return Err(crate::LoadError::InvalidVrm(format!(
1236 "node {node_index} mesh {mesh_index} primitive {primitive_index} has a non-finite value in its {source} morph weights"
1237 )));
1238 }
1239
1240 Ok(weights.to_vec())
1241}
1242
1243struct VertexBuffers {
1246 positions: Vec<[f32; 3]>,
1247 texcoord_sets: Vec<Vec<[f32; 2]>>,
1248 colors: Vec<[f32; 4]>,
1249 skinning_sets: Vec<SkinningSet>,
1250 morph_targets: Vec<MorphTarget>,
1251}
1252
1253impl VertexBuffers {
1254 fn expand(self, indices: &[u32]) -> (Self, Vec<u32>) {
1257 let expanded = Self {
1258 positions: remap(self.positions, indices),
1259 texcoord_sets: self
1260 .texcoord_sets
1261 .into_iter()
1262 .map(|set| remap(set, indices))
1263 .collect(),
1264 colors: remap(self.colors, indices),
1265 skinning_sets: self
1266 .skinning_sets
1267 .into_iter()
1268 .map(|set| {
1269 SkinningSet::new(remap(set.joints, indices), remap(set.weights, indices))
1270 })
1271 .collect(),
1272 morph_targets: remap_morph_targets(self.morph_targets, indices),
1273 };
1274 let expanded_indices: Vec<u32> = (0..expanded.positions.len() as u32).collect();
1275 (expanded, expanded_indices)
1276 }
1277}
1278
1279fn resolve_normals(
1285 vertex: VertexBuffers,
1286 indices: Vec<u32>,
1287 supplied_normals: Option<Vec<[f32; 3]>>,
1288 topology: PrimitiveTopology,
1289) -> (VertexBuffers, Vec<[f32; 3]>, Vec<u32>, bool) {
1290 match (supplied_normals, topology) {
1291 (Some(normals), _) => (vertex, normals, indices, false),
1292 (None, PrimitiveTopology::Triangles) => {
1293 let (vertex, indices) = vertex.expand(&indices);
1294 let normals = compute_flat_normals(&vertex.positions, &indices);
1295 (vertex, normals, indices, true)
1296 }
1297 (None, _) => {
1298 let normals = vec![[0.0, 0.0, 0.0]; vertex.positions.len()];
1299 (vertex, normals, indices, false)
1300 }
1301 }
1302}
1303
1304fn resolve_tangents(
1307 supplied_tangents: Option<Vec<[f32; 4]>>,
1308 has_normals: bool,
1309 normal_texture_texcoord: Option<u32>,
1310 vertex: &VertexBuffers,
1311 normals: &[[f32; 3]],
1312 indices: &[u32],
1313 topology: PrimitiveTopology,
1314) -> Vec<[f32; 4]> {
1315 match (supplied_tangents, has_normals) {
1316 (Some(supplied), true) => supplied,
1317 _ => compute_mikkts_tangents(
1318 &vertex.positions,
1319 Some(normals),
1320 normal_texture_texcoord,
1321 &vertex.texcoord_sets,
1322 indices,
1323 topology,
1324 vertex.positions.len(),
1325 ),
1326 }
1327}
1328
1329#[allow(clippy::too_many_arguments)]
1335fn resolve_loaded_tangents(
1336 _stored_tangents: Option<Vec<[f32; 4]>>,
1337 has_normals: bool,
1338 normal_texture_texcoord: Option<u32>,
1339 vertex: &VertexBuffers,
1340 normals: &[[f32; 3]],
1341 indices: &[u32],
1342 topology: PrimitiveTopology,
1343) -> Vec<[f32; 4]> {
1344 resolve_tangents(
1345 None,
1346 has_normals,
1347 normal_texture_texcoord,
1348 vertex,
1349 normals,
1350 indices,
1351 topology,
1352 )
1353}
1354
1355fn normal_texture_texcoord(material: &gltf::Material<'_>) -> Option<u32> {
1357 material.normal_texture().map(|info| {
1358 let (_, transformed_tex_coord) =
1359 crate::material::extension_transform(info.extension_value("KHR_texture_transform"));
1360 transformed_tex_coord.unwrap_or_else(|| info.tex_coord())
1361 })
1362}
1363
1364fn base_color_texture(material: &gltf::Material<'_>) -> (Option<usize>, u32) {
1367 let base_color_texture = material.pbr_metallic_roughness().base_color_texture();
1368 let texture_index = base_color_texture
1369 .as_ref()
1370 .map(|info| info.texture().index());
1371 let base_color_texcoord = base_color_texture
1372 .as_ref()
1373 .map(|info| {
1374 info.texture_transform()
1375 .and_then(|transform| transform.tex_coord())
1376 .unwrap_or_else(|| info.tex_coord())
1377 })
1378 .unwrap_or(0);
1379 (texture_index, base_color_texcoord)
1380}
1381
1382fn validate_f32_attribute<const N: usize>(
1385 name: &str,
1386 values: &[[f32; N]],
1387 vertex_count: usize,
1388 mesh_index: usize,
1389 primitive_index: usize,
1390) -> Result<(), crate::LoadError> {
1391 if values.len() != vertex_count {
1392 return Err(crate::LoadError::InvalidVrm(format!(
1393 "mesh {mesh_index} primitive {primitive_index} {name} has {} values for {vertex_count} positions",
1394 values.len()
1395 )));
1396 }
1397 if values.iter().flatten().any(|value| !value.is_finite()) {
1398 return Err(crate::LoadError::InvalidVrm(format!(
1399 "mesh {mesh_index} primitive {primitive_index} {name} contains a non-finite value"
1400 )));
1401 }
1402 Ok(())
1403}
1404
1405fn validate_morph_targets(
1408 targets: &[MorphTarget],
1409 vertex_count: usize,
1410 mesh_index: usize,
1411 primitive_index: usize,
1412) -> Result<(), crate::LoadError> {
1413 for (target, morph) in targets.iter().enumerate() {
1414 validate_f32_attribute(
1415 &format!("morph target {target} POSITION"),
1416 morph.position_deltas(),
1417 vertex_count,
1418 mesh_index,
1419 primitive_index,
1420 )?;
1421 if let Some(normals) = morph.normal_deltas() {
1422 validate_f32_attribute(
1423 &format!("morph target {target} NORMAL"),
1424 normals,
1425 vertex_count,
1426 mesh_index,
1427 primitive_index,
1428 )?;
1429 }
1430 if let Some(tangents) = morph.tangent_deltas() {
1431 validate_f32_attribute(
1432 &format!("morph target {target} TANGENT"),
1433 tangents,
1434 vertex_count,
1435 mesh_index,
1436 primitive_index,
1437 )?;
1438 }
1439 }
1440 Ok(())
1441}
1442
1443struct IndexedAttributeSets {
1445 texcoords: Vec<u32>,
1446 joints: Vec<u32>,
1447 weights: Vec<u32>,
1448}
1449
1450fn indexed_attribute_sets(
1451 primitive: &gltf::Primitive<'_>,
1452 vertex_count: usize,
1453) -> Result<IndexedAttributeSets, crate::LoadError> {
1454 use gltf::Semantic;
1455 use gltf::accessor::{DataType, Dimensions};
1456
1457 let mut texcoords = Vec::new();
1458 let mut joints = Vec::new();
1459 let mut weights = Vec::new();
1460 for (semantic, accessor) in primitive.attributes() {
1461 let valid = match semantic {
1462 Semantic::TexCoords(set) => {
1463 texcoords.push(set);
1464 accessor.dimensions() == Dimensions::Vec2
1465 && matches!(
1466 (accessor.data_type(), accessor.normalized()),
1467 (DataType::F32, false) | (DataType::U8 | DataType::U16, true)
1468 )
1469 }
1470 Semantic::Joints(set) => {
1471 joints.push(set);
1472 accessor.dimensions() == Dimensions::Vec4
1473 && matches!(accessor.data_type(), DataType::U8 | DataType::U16)
1474 && !accessor.normalized()
1475 }
1476 Semantic::Weights(set) => {
1477 weights.push(set);
1478 accessor.dimensions() == Dimensions::Vec4
1479 && matches!(
1480 (accessor.data_type(), accessor.normalized()),
1481 (DataType::F32, false) | (DataType::U8 | DataType::U16, true)
1482 )
1483 }
1484 _ => continue,
1485 };
1486 if !valid || accessor.count() != vertex_count {
1487 return Err(crate::LoadError::InvalidVrm(format!(
1488 "mesh primitive {} has an invalid {semantic:?} accessor",
1489 primitive.index()
1490 )));
1491 }
1492 }
1493
1494 for (name, sets) in [
1495 ("TEXCOORD", &mut texcoords),
1496 ("JOINTS", &mut joints),
1497 ("WEIGHTS", &mut weights),
1498 ] {
1499 sets.sort_unstable();
1500 if sets
1501 .iter()
1502 .copied()
1503 .enumerate()
1504 .any(|(expected, actual)| actual as usize != expected)
1505 {
1506 return Err(crate::LoadError::InvalidVrm(format!(
1507 "mesh primitive {} {name}_n indices must start at zero and be consecutive",
1508 primitive.index()
1509 )));
1510 }
1511 }
1512
1513 Ok(IndexedAttributeSets {
1514 texcoords,
1515 joints,
1516 weights,
1517 })
1518}
1519
1520fn validate_and_normalize_skinning_sets(
1523 skinning_sets: &mut [SkinningSet],
1524 skin: Option<(usize, usize)>,
1525 mesh_index: usize,
1526 primitive_index: usize,
1527 vertex_count: usize,
1528) -> Result<(), crate::LoadError> {
1529 if skin.is_some() && skinning_sets.is_empty() {
1530 return Err(crate::LoadError::InvalidVrm(format!(
1531 "mesh {mesh_index} primitive {primitive_index} is skinned but lacks JOINTS_0 and WEIGHTS_0"
1532 )));
1533 }
1534
1535 for vertex in 0..vertex_count {
1536 let mut weighted_joints = Vec::new();
1537 let mut total_weight = 0.0_f32;
1538 for set in skinning_sets.iter() {
1539 for (&joint, &weight) in set.joints[vertex].iter().zip(&set.weights[vertex]) {
1540 if !weight.is_finite() || weight < 0.0 {
1541 return Err(crate::LoadError::InvalidVrm(format!(
1542 "mesh {mesh_index} primitive {primitive_index} vertex {vertex} has an invalid skinning weight"
1543 )));
1544 }
1545 total_weight += weight;
1546 if weight == 0.0 {
1547 continue;
1548 }
1549 if let Some((skin_index, joint_count)) = skin
1550 && joint as usize >= joint_count
1551 {
1552 return Err(crate::LoadError::InvalidVrm(format!(
1553 "mesh {mesh_index} primitive {primitive_index} vertex {vertex} has weighted joint {joint} outside skin {skin_index}"
1554 )));
1555 }
1556 if weighted_joints.contains(&joint) {
1557 return Err(crate::LoadError::InvalidVrm(format!(
1558 "mesh {mesh_index} primitive {primitive_index} vertex {vertex} assigns joint {joint} more than one positive weight"
1559 )));
1560 }
1561 weighted_joints.push(joint);
1562 }
1563 }
1564
1565 if !total_weight.is_finite() {
1566 return Err(crate::LoadError::InvalidVrm(format!(
1567 "mesh {mesh_index} primitive {primitive_index} vertex {vertex} has a non-finite total skinning weight"
1568 )));
1569 }
1570 if total_weight > 0.0 {
1571 for set in skinning_sets.iter_mut() {
1574 for weight in &mut set.weights[vertex] {
1575 *weight /= total_weight;
1576 }
1577 }
1578 }
1579 }
1580 Ok(())
1581}
1582
1583fn read_texcoords(
1585 texcoords: Option<gltf::mesh::util::ReadTexCoords<'_>>,
1586 _vertex_count: usize,
1587) -> Option<Vec<[f32; 2]>> {
1588 texcoords.map(|texcoords| texcoords.into_f32().collect())
1589}
1590
1591fn read_colors(
1594 colors: Option<gltf::mesh::util::ReadColors<'_>>,
1595 vertex_count: usize,
1596) -> Vec<[f32; 4]> {
1597 colors
1598 .map(|colors| colors.into_rgba_f32().collect())
1599 .unwrap_or_else(|| vec![[1.0, 1.0, 1.0, 1.0]; vertex_count])
1600}
1601
1602fn read_joints(
1605 joints: Option<gltf::mesh::util::ReadJoints<'_>>,
1606 _vertex_count: usize,
1607) -> Option<Vec<[u16; 4]>> {
1608 joints.map(|joints| joints.into_u16().collect())
1609}
1610
1611fn read_weights(
1613 weights: Option<gltf::mesh::util::ReadWeights<'_>>,
1614 _vertex_count: usize,
1615) -> Option<Vec<[f32; 4]>> {
1616 weights.map(|weights| weights.into_f32().collect())
1617}
1618
1619fn read_morph_targets<'a, 's, F>(
1622 reader: &gltf::mesh::Reader<'a, 's, F>,
1623 vertex_count: usize,
1624) -> Vec<MorphTarget>
1625where
1626 F: Clone + Fn(gltf::Buffer<'a>) -> Option<&'s [u8]>,
1627{
1628 reader
1629 .read_morph_targets()
1630 .map(|(target_positions, target_normals, _target_tangents)| {
1631 let position_deltas = target_positions
1632 .map(|deltas| deltas.collect())
1633 .unwrap_or_else(|| vec![[0.0, 0.0, 0.0]; vertex_count]);
1634 MorphTarget::new(
1635 position_deltas,
1636 target_normals.map(|deltas| deltas.collect()),
1637 None,
1641 )
1642 })
1643 .collect()
1644}
1645
1646fn normalize_topology(mode: gltf::mesh::Mode, indices: Vec<u32>) -> (PrimitiveTopology, Vec<u32>) {
1652 use gltf::mesh::Mode;
1653 match mode {
1654 Mode::Points => (PrimitiveTopology::Points, indices),
1655 Mode::Lines => (PrimitiveTopology::Lines, indices),
1656 Mode::LineStrip => (PrimitiveTopology::LineStrip, indices),
1657 Mode::LineLoop => {
1660 let mut indices = indices;
1661 if let Some(first) = indices.first().copied() {
1662 indices.push(first);
1663 }
1664 (PrimitiveTopology::LineStrip, indices)
1665 }
1666 Mode::Triangles => (PrimitiveTopology::Triangles, indices),
1667 Mode::TriangleStrip => {
1668 let mut triangles = Vec::with_capacity(indices.len().saturating_sub(2) * 3);
1669 for i in 0..indices.len().saturating_sub(2) {
1670 if i % 2 == 0 {
1671 triangles.extend_from_slice(&[indices[i], indices[i + 1], indices[i + 2]]);
1672 } else {
1673 triangles.extend_from_slice(&[indices[i + 1], indices[i], indices[i + 2]]);
1674 }
1675 }
1676 (PrimitiveTopology::Triangles, triangles)
1677 }
1678 Mode::TriangleFan => {
1679 let mut triangles = Vec::with_capacity(indices.len().saturating_sub(2) * 3);
1680 for i in 1..indices.len().saturating_sub(1) {
1681 triangles.extend_from_slice(&[indices[0], indices[i], indices[i + 1]]);
1682 }
1683 (PrimitiveTopology::Triangles, triangles)
1684 }
1685 }
1686}
1687
1688fn remap<T: Clone>(values: Vec<T>, indices: &[u32]) -> Vec<T> {
1691 indices
1692 .iter()
1693 .map(|&i| values[i as usize].clone())
1694 .collect()
1695}
1696
1697fn remap_morph_targets(mut morph_targets: Vec<MorphTarget>, indices: &[u32]) -> Vec<MorphTarget> {
1702 for target in &mut morph_targets {
1703 let positions: Vec<[f32; 3]> = indices
1704 .iter()
1705 .map(|&i| target.position_deltas()[i as usize])
1706 .collect();
1707 let normals: Option<Vec<[f32; 3]>> = target
1708 .normal_deltas()
1709 .map(|values| indices.iter().map(|&i| values[i as usize]).collect());
1710 *target = MorphTarget::new(positions, normals, None);
1711 }
1712 morph_targets
1713}
1714
1715fn compute_flat_normals(positions: &[[f32; 3]], indices: &[u32]) -> Vec<[f32; 3]> {
1720 let mut normals = vec![[0.0, 0.0, 0.0]; positions.len()];
1721
1722 for tri in indices.chunks_exact(3) {
1723 if let [a, b, c] = *tri {
1724 let p0 = glam::Vec3::from_array(positions[a as usize]);
1725 let p1 = glam::Vec3::from_array(positions[b as usize]);
1726 let p2 = glam::Vec3::from_array(positions[c as usize]);
1727
1728 let n = (p1 - p0).cross(p2 - p0).normalize_or_zero();
1729
1730 normals[a as usize] = n.to_array();
1731 normals[b as usize] = n.to_array();
1732 normals[c as usize] = n.to_array();
1733 }
1734 }
1735
1736 normals
1737}
1738
1739#[allow(clippy::too_many_arguments)]
1746fn compute_mikkts_tangents(
1747 positions: &[[f32; 3]],
1748 normals: Option<&[[f32; 3]]>,
1749 normal_texture_texcoord: Option<u32>,
1750 texcoord_sets: &[Vec<[f32; 2]>],
1751 indices: &[u32],
1752 topology: PrimitiveTopology,
1753 vertex_count: usize,
1754) -> Vec<[f32; 4]> {
1755 let placeholder = || vec![[1.0, 0.0, 0.0, 1.0]; vertex_count];
1756
1757 if topology != PrimitiveTopology::Triangles {
1758 return placeholder();
1759 }
1760 let Some(normals) = normals else {
1761 return placeholder();
1762 };
1763 let Some(normal_texcoord) = normal_texture_texcoord else {
1764 return placeholder();
1765 };
1766
1767 let Some(uvs) = texcoord_sets
1769 .get(normal_texcoord as usize)
1770 .map(Vec::as_slice)
1771 else {
1772 return placeholder();
1773 };
1774
1775 let mut geometry = MikktsGeometry {
1776 positions,
1777 normals,
1778 uvs,
1779 indices,
1780 tangents: vec![[1.0, 0.0, 0.0, 1.0]; vertex_count],
1781 };
1782
1783 if mikktspace::generate_tangents(&mut geometry) {
1784 geometry.tangents
1785 } else {
1786 placeholder()
1787 }
1788}
1789
1790struct MikktsGeometry<'a> {
1792 positions: &'a [[f32; 3]],
1793 normals: &'a [[f32; 3]],
1794 uvs: &'a [[f32; 2]],
1795 indices: &'a [u32],
1796 tangents: Vec<[f32; 4]>,
1797}
1798
1799impl mikktspace::Geometry for MikktsGeometry<'_> {
1800 fn num_faces(&self) -> usize {
1801 self.indices.len() / 3
1802 }
1803
1804 fn num_vertices_of_face(&self, _face: usize) -> usize {
1805 3
1806 }
1807
1808 fn position(&self, face: usize, vert: usize) -> [f32; 3] {
1809 self.positions[self.indices[face * 3 + vert] as usize]
1810 }
1811
1812 fn normal(&self, face: usize, vert: usize) -> [f32; 3] {
1813 self.normals[self.indices[face * 3 + vert] as usize]
1814 }
1815
1816 fn tex_coord(&self, face: usize, vert: usize) -> [f32; 2] {
1817 self.uvs[self.indices[face * 3 + vert] as usize]
1818 }
1819
1820 fn set_tangent(
1821 &mut self,
1822 tangent: [f32; 3],
1823 _bi_tangent: [f32; 3],
1824 _f_mag_s: f32,
1825 _f_mag_t: f32,
1826 bi_tangent_preserves_orientation: bool,
1827 face: usize,
1828 vert: usize,
1829 ) {
1830 let index = self.indices[face * 3 + vert] as usize;
1831 let w = if bi_tangent_preserves_orientation {
1832 1.0
1833 } else {
1834 -1.0
1835 };
1836 self.tangents[index] = [tangent[0], tangent[1], tangent[2], w];
1837 }
1838}
1839
1840#[cfg(test)]
1841mod tests {
1842 use super::{
1843 MorphTarget, MorphedVertices, PrimitiveTopology, RenderPrimitive, base_color_texture,
1844 compute_flat_normals, compute_mikkts_tangents, load_primitives, normal_texture_texcoord,
1845 normalize_topology, resolve_loaded_tangents, resolve_morph_weights,
1846 };
1847 use crate::Transform;
1848
1849 #[test]
1850 fn flat_normals_follow_triangle_winding() {
1851 let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
1852 let indices = vec![0u32, 1, 2];
1853
1854 let normals = compute_flat_normals(&positions, &indices);
1855
1856 for n in &normals {
1857 assert_eq!(n, &[0.0, 0.0, 1.0], "CCW winding should face +Z");
1858 }
1859 }
1860
1861 #[test]
1862 fn flat_normals_are_unit_length() {
1863 let positions = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 0.0, 2.0]];
1864 let indices = vec![0u32, 1, 2];
1865
1866 let normals = compute_flat_normals(&positions, &indices);
1867
1868 for n in &normals {
1869 let len = (n[0].powi(2) + n[1].powi(2) + n[2].powi(2)).sqrt();
1870 assert!(
1871 (len - 1.0).abs() < 1e-6,
1872 "normal should have unit length: {n:?}"
1873 );
1874 }
1875 }
1876
1877 #[test]
1878 fn degenerate_triangle_yields_zero_normal() {
1879 let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]];
1880 let indices = vec![0u32, 1, 2];
1881
1882 let normals = compute_flat_normals(&positions, &indices);
1883
1884 assert_eq!(normals[0], [0.0, 0.0, 0.0]);
1885 }
1886
1887 #[test]
1888 fn triangle_strip_is_normalized_with_gl_tf_winding() {
1889 let (topology, indices) =
1890 normalize_topology(gltf::mesh::Mode::TriangleStrip, vec![0, 1, 2, 3]);
1891
1892 assert_eq!(topology, PrimitiveTopology::Triangles);
1893 assert_eq!(indices, vec![0, 1, 2, 2, 1, 3]);
1894 }
1895
1896 #[test]
1897 fn line_loop_becomes_closed_line_strip() {
1898 let (topology, indices) = normalize_topology(gltf::mesh::Mode::LineLoop, vec![4, 5, 6]);
1899
1900 assert_eq!(topology, PrimitiveTopology::LineStrip);
1901 assert_eq!(indices, vec![4, 5, 6, 4]);
1902 }
1903
1904 #[test]
1905 fn primitive_traversal_handles_a_deep_node_chain_iteratively() {
1906 const NODE_COUNT: usize = 20_000;
1907 let nodes = (0..NODE_COUNT)
1908 .map(|index| {
1909 if index + 1 == NODE_COUNT {
1910 serde_json::json!({})
1911 } else {
1912 serde_json::json!({ "children": [index + 1] })
1913 }
1914 })
1915 .collect::<Vec<_>>();
1916 let bytes = serde_json::to_vec(&serde_json::json!({
1917 "asset": { "version": "2.0" },
1918 "nodes": nodes,
1919 "scenes": [{ "nodes": [0] }],
1920 "scene": 0
1921 }))
1922 .expect("the deep glTF fixture must serialize");
1923 let gltf = gltf::Gltf::from_slice_without_validation(&bytes)
1924 .expect("the deep glTF fixture must parse");
1925
1926 let primitives = load_primitives(&gltf.document, &[])
1927 .expect("iterative traversal must not overflow the call stack");
1928
1929 assert!(primitives.is_empty());
1930 }
1931
1932 #[test]
1933 fn loaded_morph_weights_must_be_finite() {
1934 let error = resolve_morph_weights(Some(&[f32::NAN]), None, 1, 2, 3, 4)
1935 .expect_err("non-finite node morph weights must be rejected");
1936
1937 assert!(
1938 matches!(
1939 error,
1940 crate::LoadError::InvalidVrm(ref message)
1941 if message.contains("node 2 mesh 3 primitive 4")
1942 && message.contains("non-finite")
1943 && message.contains("node morph weights")
1944 ),
1945 "{error}"
1946 );
1947 }
1948
1949 #[test]
1950 fn mikkts_generates_tangent_from_uv_layout() {
1951 let positions = [
1954 [0.0, 0.0, 0.0],
1955 [1.0, 0.0, 0.0],
1956 [1.0, 1.0, 0.0],
1957 [0.0, 1.0, 0.0],
1958 ];
1959 let normals = [[0.0, 0.0, 1.0]; 4];
1960 let texcoords = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
1961 let indices = vec![0u32, 1, 2, 0, 2, 3];
1962
1963 let tangents = compute_mikkts_tangents(
1964 &positions,
1965 Some(&normals),
1966 Some(2),
1967 &[
1968 vec![[0.0, 0.0]; positions.len()],
1969 vec![[0.0, 0.0]; positions.len()],
1970 texcoords.to_vec(),
1971 ],
1972 &indices,
1973 PrimitiveTopology::Triangles,
1974 positions.len(),
1975 );
1976
1977 for t in &tangents {
1978 assert!(
1979 (t[0] - 1.0).abs() < 1e-4 && t[1].abs() < 1e-4 && t[2].abs() < 1e-4,
1980 "tangent should point along +X: {t:?}"
1981 );
1982 assert_eq!(t[3], 1.0, "frame should be right-handed");
1983 }
1984 }
1985
1986 #[test]
1987 fn mikkts_skips_without_normals_or_uv_set() {
1988 let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
1989 let indices = vec![0u32, 1, 2];
1990
1991 let tangents = compute_mikkts_tangents(
1993 &positions,
1994 None,
1995 Some(0),
1996 &[vec![[0.0, 0.0]; 3]],
1997 &indices,
1998 PrimitiveTopology::Triangles,
1999 positions.len(),
2000 );
2001 assert_eq!(tangents, vec![[1.0, 0.0, 0.0, 1.0]; 3]);
2002
2003 let tangents = compute_mikkts_tangents(
2005 &positions,
2006 Some(&[[0.0, 0.0, 1.0]; 3]),
2007 Some(2),
2008 &[vec![[0.0, 0.0]; 3], vec![[0.0, 0.0]; 3]],
2009 &indices,
2010 PrimitiveTopology::Triangles,
2011 positions.len(),
2012 );
2013 assert_eq!(tangents, vec![[1.0, 0.0, 0.0, 1.0]; 3]);
2014 }
2015
2016 #[test]
2017 fn loaded_tangent_policy_ignores_the_stored_stream() {
2018 let vertex = super::VertexBuffers {
2019 positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
2020 texcoord_sets: vec![vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]],
2021 colors: vec![[1.0; 4]; 3],
2022 skinning_sets: Vec::new(),
2023 morph_targets: Vec::new(),
2024 };
2025 let normals = [[0.0, 0.0, 1.0]; 3];
2026 let stored = vec![[-1.0, 0.0, 0.0, -1.0]; 3];
2027
2028 let tangents = resolve_loaded_tangents(
2029 Some(stored),
2030 true,
2031 Some(0),
2032 &vertex,
2033 &normals,
2034 &[0, 1, 2],
2035 PrimitiveTopology::Triangles,
2036 );
2037
2038 for tangent in tangents {
2039 assert!(tangent[0] > 0.99, "MikkTSpace should replace stored data");
2040 assert_eq!(tangent[3], 1.0);
2041 }
2042 }
2043
2044 #[test]
2045 fn normal_texture_transform_uv_override_drives_tangent_generation() {
2046 let document = serde_json::json!({
2047 "asset": { "version": "2.0" },
2048 "extensionsUsed": ["KHR_texture_transform"],
2049 "images": [{ "uri": "normal.png" }],
2050 "textures": [{ "source": 0 }],
2051 "materials": [{
2052 "normalTexture": {
2053 "index": 0,
2054 "texCoord": 0,
2055 "extensions": {
2056 "KHR_texture_transform": { "texCoord": 1 }
2057 }
2058 }
2059 }]
2060 });
2061 let bytes = serde_json::to_vec(&document).expect("the test document must serialize");
2062 let gltf = gltf::Gltf::from_slice(&bytes).expect("the test document must parse");
2063 let material = gltf
2064 .document
2065 .materials()
2066 .next()
2067 .expect("the test material must exist");
2068
2069 assert_eq!(normal_texture_texcoord(&material), Some(1));
2070 }
2071
2072 #[test]
2073 fn base_color_shortcut_uses_texture_id_and_transformed_uv_set() {
2074 let document = serde_json::json!({
2075 "asset": { "version": "2.0" },
2076 "extensionsUsed": ["KHR_texture_transform"],
2077 "images": [{ "uri": "unused.png" }, { "uri": "base.png" }],
2078 "textures": [{ "source": 1 }],
2079 "materials": [{
2080 "pbrMetallicRoughness": {
2081 "baseColorTexture": {
2082 "index": 0,
2083 "texCoord": 0,
2084 "extensions": {
2085 "KHR_texture_transform": { "texCoord": 1 }
2086 }
2087 }
2088 }
2089 }]
2090 });
2091 let bytes = serde_json::to_vec(&document).expect("the test document must serialize");
2092 let gltf = gltf::Gltf::from_slice(&bytes).expect("the test document must parse");
2093 let material = gltf
2094 .document
2095 .materials()
2096 .next()
2097 .expect("the test material must exist");
2098
2099 assert_eq!(base_color_texture(&material), (Some(0), 1));
2100 }
2101
2102 #[test]
2103 fn morphing_moves_positions_by_weighted_deltas() {
2104 let mut primitive = RenderPrimitive::new(
2105 0,
2106 Transform::IDENTITY,
2107 vec![[0.0, 0.0, 0.0]],
2108 vec![[0.0, 0.0, 1.0]],
2109 vec![0],
2110 vec![[0; 4]],
2111 vec![[0.0; 4]],
2112 vec![MorphTarget::new(vec![[1.0, 0.0, 0.0]], None, None)],
2113 vec![[0.0, 0.0]],
2114 vec![[1.0, 0.0, 0.0, 1.0]],
2115 vec![[1.0; 4]],
2116 vec![[0.0, 0.0]],
2117 None,
2118 None,
2119 PrimitiveTopology::Triangles,
2120 vec![],
2121 false,
2122 None,
2123 0,
2124 );
2125
2126 primitive.set_morph_weights(&[0.5]);
2127 let MorphedVertices { positions, .. } = primitive.morphed_vertices();
2128 assert_eq!(positions[0], [0.5, 0.0, 0.0]);
2129 }
2130
2131 #[test]
2132 fn morphing_renormalizes_smooth_normals_with_deltas() {
2133 let mut primitive = RenderPrimitive::new(
2134 0,
2135 Transform::IDENTITY,
2136 vec![[0.0, 0.0, 0.0]],
2137 vec![[0.0, 0.0, 1.0]],
2138 vec![0],
2139 vec![[0; 4]],
2140 vec![[0.0; 4]],
2141 vec![MorphTarget::new(
2142 vec![[0.0, 0.0, 0.0]],
2143 Some(vec![[0.0, 0.0, 1.0]]),
2144 None,
2145 )],
2146 vec![[0.0, 0.0]],
2147 vec![[1.0, 0.0, 0.0, 1.0]],
2148 vec![[1.0; 4]],
2149 vec![[0.0, 0.0]],
2150 None,
2151 None,
2152 PrimitiveTopology::Triangles,
2153 vec![],
2154 false,
2155 None,
2156 0,
2157 );
2158
2159 primitive.set_morph_weights(&[1.0]);
2161 let MorphedVertices { normals, .. } = primitive.morphed_vertices();
2162 assert_eq!(normals[0], [0.0, 0.0, 1.0]);
2163 }
2164
2165 #[test]
2166 fn morphing_recomputes_flat_normals_from_morphed_positions() {
2167 let positions = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0]];
2169 let indices = vec![0u32, 1, 2];
2170 let mut primitive = RenderPrimitive::new(
2171 0,
2172 Transform::IDENTITY,
2173 positions,
2174 vec![[0.0, 0.0, 1.0]; 3],
2175 indices,
2176 vec![[0; 4]; 3],
2177 vec![[0.0; 4]; 3],
2178 vec![MorphTarget::new(
2179 vec![[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, -1.0, 1.0]],
2180 None,
2181 None,
2182 )],
2183 vec![[0.0, 0.0]; 3],
2184 vec![[1.0, 0.0, 0.0, 1.0]; 3],
2185 vec![[1.0; 4]; 3],
2186 vec![[0.0, 0.0]; 3],
2187 None,
2188 None,
2189 PrimitiveTopology::Triangles,
2190 vec![],
2191 true,
2192 None,
2193 0,
2194 );
2195
2196 primitive.set_morph_weights(&[1.0]);
2200 let MorphedVertices { normals, .. } = primitive.morphed_vertices();
2201 assert_eq!(
2202 normals[0],
2203 [0.0, -1.0, 0.0],
2204 "raised vertex should reorient the flat normal"
2205 );
2206 }
2207}