diff --git a/crates/formats/src/mesh_import/ply.rs b/crates/formats/src/mesh_import/ply.rs index 0a72b28e..34e1c1da 100644 --- a/crates/formats/src/mesh_import/ply.rs +++ b/crates/formats/src/mesh_import/ply.rs @@ -117,7 +117,8 @@ pub(crate) fn read(bytes: &[u8]) -> Result { let mut body = Body { data: bytes.get(body_start..).unwrap_or_default(), pos: 0, enc }; let mut raw = RawMesh::default(); let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new()); - let mut nverts = 0usize; + // Elements may appear in any order, so take the vertex count from the header. + let nverts: usize = elements.iter().filter(|e| e.name == "vertex").map(|e| e.count).fold(0, usize::saturating_add); for el in &elements { // Every item takes at least one byte, so the count can never exceed what is left. if el.count > body.remaining() { @@ -137,7 +138,6 @@ pub(crate) fn read(bytes: &[u8]) -> Result { return Err(malformed(KIND, "vertices have no x, y, z")); } check_vertices(el.count)?; - nverts = el.count; raw.positions.reserve(el.count); } let face_list = diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index 752fa61b..5d911e66 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -485,3 +485,13 @@ fn gltf_cameras_become_orbit_cameras() { assert!(near(top.pitch, 89f32.to_radians()), "looking down, pitch clamped: {top:?}"); assert!(import_mesh_bytes("scene.gltf", &embedded_gltf()).unwrap().cameras.is_empty()); } + +#[test] +fn ply_face_element_before_vertex_element() { + let head = "ply\nformat ascii 1.0\nelement face 1\nproperty list uchar int vertex_indices\nelement vertex 3\nproperty float x\nproperty float y\nproperty float z\nend_header\n"; + let ok = format!("{head}3 0 1 2\n0 0 0\n1 0 0\n0 1 0\n"); + let mesh = import_mesh_bytes("a.ply", ok.as_bytes()).unwrap().mesh; + assert_eq!(mesh.positions.len(), 3); + let bad = format!("{head}3 0 1 5\n0 0 0\n1 0 0\n0 1 0\n"); + assert!(import_mesh_bytes("a.ply", bad.as_bytes()).is_err()); +}