1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
use crate::geometry_indices::{FaceIndex, PointIndex};
use crate::point_cloud::PointCloud;
use crate::status::{DracoError, Status};
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
/// Triangle face represented by three point indices.
pub type Face = [PointIndex; 3];
/// Triangle mesh geometry decoded from, or prepared for, a Draco bitstream.
///
/// A mesh owns triangle topology and dereferences to its underlying
/// [`PointCloud`], where attributes and metadata are stored.
#[derive(Debug, Default, Clone)]
pub struct Mesh {
point_cloud: PointCloud,
faces: Vec<Face>,
}
impl Mesh {
/// Creates an empty mesh with no faces, points, attributes, or metadata.
pub fn new() -> Self {
Self::default()
}
/// Appends one triangle face.
pub fn add_face(&mut self, face: Face) {
self.faces.push(face);
}
/// Sets a face, growing the face list with zeroed faces when needed.
pub fn set_face(&mut self, face_id: FaceIndex, face: Face) {
if face_id.0 as usize >= self.faces.len() {
self.faces
.resize(face_id.0 as usize + 1, [PointIndex(0); 3]);
}
self.faces[face_id.0 as usize] = face;
}
/// Bulk-set all faces from a flat u32 index array (3 indices per face).
/// Assumes `set_num_faces` has already been called with the right count.
#[inline]
pub fn set_faces_from_flat_indices(&mut self, indices: &[u32]) {
debug_assert_eq!(indices.len(), self.faces.len() * 3);
for (i, face) in self.faces.iter_mut().enumerate() {
let base = i * 3;
*face = [
PointIndex(indices[base]),
PointIndex(indices[base + 1]),
PointIndex(indices[base + 2]),
];
}
}
/// Bulk-set all faces from tightly packed u8 indices.
/// Assumes `set_num_faces` has already been called with the right count.
#[inline]
pub fn set_faces_from_u8_indices(&mut self, bytes: &[u8]) {
debug_assert_eq!(bytes.len(), self.faces.len() * 3);
for (face, chunk) in self.faces.iter_mut().zip(bytes.chunks_exact(3)) {
*face = [
PointIndex(chunk[0] as u32),
PointIndex(chunk[1] as u32),
PointIndex(chunk[2] as u32),
];
}
}
/// Bulk-set all faces from tightly packed little-endian u16 indices.
/// Assumes `set_num_faces` has already been called with the right count.
#[inline]
pub fn set_faces_from_le_u16_indices(&mut self, bytes: &[u8]) {
debug_assert_eq!(bytes.len(), self.faces.len() * 3 * 2);
for (face, chunk) in self.faces.iter_mut().zip(bytes.chunks_exact(6)) {
*face = [
PointIndex(u16::from_le_bytes([chunk[0], chunk[1]]) as u32),
PointIndex(u16::from_le_bytes([chunk[2], chunk[3]]) as u32),
PointIndex(u16::from_le_bytes([chunk[4], chunk[5]]) as u32),
];
}
}
/// Bulk-set all faces from tightly packed little-endian u32 indices.
/// Assumes `set_num_faces` has already been called with the right count.
#[inline]
pub fn set_faces_from_le_u32_indices(&mut self, bytes: &[u8]) {
debug_assert_eq!(bytes.len(), self.faces.len() * 3 * 4);
for (face, chunk) in self.faces.iter_mut().zip(bytes.chunks_exact(12)) {
*face = [
PointIndex(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])),
PointIndex(u32::from_le_bytes([chunk[4], chunk[5], chunk[6], chunk[7]])),
PointIndex(u32::from_le_bytes([
chunk[8], chunk[9], chunk[10], chunk[11],
])),
];
}
}
/// Sets one face from raw u32 point ids.
#[inline]
pub fn set_face_from_indices(&mut self, face_id: usize, indices: [u32; 3]) {
self.faces[face_id] = [
PointIndex(indices[0]),
PointIndex(indices[1]),
PointIndex(indices[2]),
];
}
/// Returns the point indices for a face.
pub fn face(&self, face_id: FaceIndex) -> Face {
self.faces[face_id.0 as usize]
}
/// Returns the number of triangle faces.
pub fn num_faces(&self) -> usize {
self.faces.len()
}
/// Resizes the face list, filling new faces with point index zero.
pub fn set_num_faces(&mut self, num_faces: usize) {
self.faces.resize(num_faces, [PointIndex(0); 3]);
}
/// Fallibly resizes the face list.
pub fn try_set_num_faces(&mut self, num_faces: usize) -> Status {
if num_faces > self.faces.len() {
self.faces
.try_reserve_exact(num_faces - self.faces.len())
.map_err(|_| DracoError::DracoError("Failed to allocate mesh faces".to_string()))?;
}
self.faces.resize(num_faces, [PointIndex(0); 3]);
Ok(())
}
/// Deduplicate point IDs to match C++ Draco behavior.
///
/// This function remaps point indices such that:
/// 1. Points are assigned new IDs in the order they're first encountered in faces
/// 2. Face indices are updated to use the new point IDs
/// 3. Attribute point mappings are updated accordingly
///
/// This is needed for binary compatibility with C++ Draco, which internally
/// creates separate points for each face corner during OBJ loading and then
/// deduplicates them in face-traversal order.
pub fn deduplicate_point_ids(&mut self) {
if self.faces.is_empty() || self.num_points() == 0 {
return;
}
// Build mapping from old point ID to new point ID
// Points are assigned new IDs in the order they're first seen in faces
let mut old_to_new: HashMap<u32, u32> = HashMap::new();
let mut new_id = 0u32;
// First pass: determine the mapping
for face in &self.faces {
for &point_idx in face.iter() {
if let std::collections::hash_map::Entry::Vacant(e) = old_to_new.entry(point_idx.0)
{
e.insert(new_id);
new_id += 1;
}
}
}
// If no remapping needed (already in correct order), skip
let needs_remap = old_to_new.iter().any(|(&old, &new)| old != new);
if !needs_remap {
return;
}
// Build reverse mapping for reordering attributes
let num_unique = new_id as usize;
let mut new_to_old = vec![0u32; num_unique];
for (&old, &new) in &old_to_new {
new_to_old[new as usize] = old;
}
// Second pass: update face indices
for face in &mut self.faces {
for point_idx in face.iter_mut() {
point_idx.0 = old_to_new[&point_idx.0];
}
}
// Third pass: reorder attribute data
// For each attribute, create new buffer with data in new order
for att_idx in 0..self.num_attributes() {
let att = self.attribute(att_idx);
let stride = att.byte_stride() as usize;
let old_buffer = att.buffer().data().to_vec();
// Create new buffer with reordered data
let mut new_buffer = vec![0u8; num_unique * stride];
for new_idx in 0..num_unique {
let old_idx = new_to_old[new_idx] as usize;
if old_idx * stride + stride <= old_buffer.len() {
new_buffer[new_idx * stride..new_idx * stride + stride]
.copy_from_slice(&old_buffer[old_idx * stride..old_idx * stride + stride]);
}
}
// Update attribute buffer - resize and write the new data
let att_mut = self.attribute_mut(att_idx);
att_mut.buffer_mut().resize(new_buffer.len());
att_mut.buffer_mut().write(0, &new_buffer);
}
// Update point count
self.set_num_points(num_unique);
}
}
impl Deref for Mesh {
type Target = PointCloud;
fn deref(&self) -> &Self::Target {
&self.point_cloud
}
}
impl DerefMut for Mesh {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.point_cloud
}
}