1use bytemuck::{Pod, Zeroable};
10
11use super::section::SectionType;
12
13pub const MAGIC_MRP1: [u8; 4] = *b"MRP1";
15
16pub const MORPH_SECTION_VERSION: u16 = 1;
18
19pub const MORPH_SECTION_HEADER_SIZE: usize = 32;
21
22pub const QUANTIZED_MORPH_DELTA_SIZE: usize = 16;
24
25pub const MAX_MORPH_TARGETS: usize = 256;
27
28pub const MAX_MORPH_DELTAS: usize = 1_048_576;
30
31pub const FLAG_MORPH_SPARSE: u32 = 1 << 0;
33pub const FLAG_MORPH_DENSE: u32 = 1 << 1;
34pub const FLAG_MORPH_HAS_NORMALS: u32 = 1 << 2;
35pub const FLAG_MORPH_HAS_TANGENTS: u32 = 1 << 3;
36pub const FLAG_MORPH_ONTOGENETIC_BIND: u32 = 1 << 4;
37
38impl SectionType {
39 pub const MORPH_TARGETS_DISCRIMINANT: u16 = 0x0013;
41
42 #[allow(non_upper_case_globals)]
44 pub const MorphTargets: Self = Self::FieldSidecar;
45}
46
47#[repr(C)]
49#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
50pub struct MorphSectionHeader {
51 pub magic: [u8; 4],
52 pub version: u16,
53 pub target_count: u16,
54 pub vertex_count: u32,
55 pub flags: u32,
56 pub max_displacement: f32,
57 pub ontogenetic_bind_mask: u32,
58 pub reserved: [u8; 8],
59}
60
61const _: [(); MORPH_SECTION_HEADER_SIZE] = [(); core::mem::size_of::<MorphSectionHeader>()];
62
63#[repr(C)]
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Pod, Zeroable)]
73pub struct QuantizedMorphDelta {
74 pub pos_delta: [i16; 3],
75 pub norm_delta: [i8; 3],
76 pub target_index: u8,
77 pub tangent_oct_delta: [i8; 2],
78 pub vertex_index: u32,
79}
80
81const _: [(); QUANTIZED_MORPH_DELTA_SIZE] = [(); core::mem::size_of::<QuantizedMorphDelta>()];
82
83#[derive(Debug, Clone, PartialEq, Eq)]
85pub enum MorphSectionError {
86 PayloadTooShort { need: usize, have: usize },
87 BadMagic([u8; 4]),
88 UnsupportedVersion(u16),
89 NonZeroReserved,
90 InvalidHeaderCounts { target_count: u16, vertex_count: u32 },
91 InvalidMaxDisplacement,
92 TooManyDeltas { count: usize, max: usize },
93 PayloadLengthMismatch { payload_len: usize },
94 BufferTooSmall { need: usize, have: usize },
95 DeltaTargetOutOfRange { index: usize, target_index: u8, target_count: u16 },
96 DeltaVertexOutOfRange { index: usize, vertex_index: u32, vertex_count: u32 },
97}
98
99impl std::fmt::Display for MorphSectionError {
100 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101 match self {
102 Self::PayloadTooShort { need, have } => {
103 write!(f, "MRP1 payload too short: have {have}, need {need}")
104 }
105 Self::BadMagic(m) => write!(f, "MRP1 bad magic: {m:?}"),
106 Self::UnsupportedVersion(v) => write!(f, "MRP1 unsupported version: {v}"),
107 Self::NonZeroReserved => write!(f, "MRP1 header reserved bytes must be zero"),
108 Self::InvalidHeaderCounts {
109 target_count,
110 vertex_count,
111 } => write!(
112 f,
113 "MRP1 invalid counts: target_count={target_count}, vertex_count={vertex_count}"
114 ),
115 Self::InvalidMaxDisplacement => {
116 write!(f, "MRP1 max_displacement must be finite and >= 0")
117 }
118 Self::TooManyDeltas { count, max } => {
119 write!(f, "MRP1 delta count {count} exceeds maximum {max}")
120 }
121 Self::PayloadLengthMismatch { payload_len } => {
122 write!(f, "MRP1 payload length {payload_len} is not aligned to 16B records")
123 }
124 Self::BufferTooSmall { need, have } => {
125 write!(f, "MRP1 output buffer too small: have {have}, need {need}")
126 }
127 Self::DeltaTargetOutOfRange {
128 index,
129 target_index,
130 target_count,
131 } => write!(
132 f,
133 "MRP1 delta[{index}] target_index {target_index} >= target_count {target_count}"
134 ),
135 Self::DeltaVertexOutOfRange {
136 index,
137 vertex_index,
138 vertex_count,
139 } => write!(
140 f,
141 "MRP1 delta[{index}] vertex_index {vertex_index} >= vertex_count {vertex_count}"
142 ),
143 }
144 }
145}
146
147impl std::error::Error for MorphSectionError {}
148
149#[inline]
151pub const fn morph_section_encoded_len(delta_count: usize) -> Option<usize> {
152 if delta_count > MAX_MORPH_DELTAS {
153 return None;
154 }
155 match delta_count.checked_mul(QUANTIZED_MORPH_DELTA_SIZE) {
156 Some(body) => MORPH_SECTION_HEADER_SIZE.checked_add(body),
157 None => None,
158 }
159}
160
161#[inline]
163pub fn quantize_morph_delta(
164 pos_delta: [f32; 3],
165 norm_delta: [f32; 3],
166 tangent_delta: [f32; 3],
167 max_displacement: f32,
168 target_index: u8,
169 vertex_index: u32,
170) -> QuantizedMorphDelta {
171 let inv_scale = if max_displacement > 1e-8 {
172 32767.0 / max_displacement
173 } else {
174 0.0
175 };
176 let q_pos = [
177 (pos_delta[0] * inv_scale).round().clamp(-32767.0, 32767.0) as i16,
178 (pos_delta[1] * inv_scale).round().clamp(-32767.0, 32767.0) as i16,
179 (pos_delta[2] * inv_scale).round().clamp(-32767.0, 32767.0) as i16,
180 ];
181 let q_norm = [
182 (norm_delta[0] * 63.5).round().clamp(-127.0, 127.0) as i8,
183 (norm_delta[1] * 63.5).round().clamp(-127.0, 127.0) as i8,
184 (norm_delta[2] * 63.5).round().clamp(-127.0, 127.0) as i8,
185 ];
186 let q_tan = [
187 (tangent_delta[0] * 63.5).round().clamp(-127.0, 127.0) as i8,
188 (tangent_delta[1] * 63.5).round().clamp(-127.0, 127.0) as i8,
189 ];
190 QuantizedMorphDelta {
191 pos_delta: q_pos,
192 norm_delta: q_norm,
193 target_index,
194 tangent_oct_delta: q_tan,
195 vertex_index,
196 }
197}
198
199#[inline]
201pub fn dequantize_morph_delta(
202 delta: &QuantizedMorphDelta,
203 max_displacement: f32,
204) -> ([f32; 3], [f32; 3]) {
205 let scale = max_displacement / 32767.0;
206 let pos = [
207 delta.pos_delta[0] as f32 * scale,
208 delta.pos_delta[1] as f32 * scale,
209 delta.pos_delta[2] as f32 * scale,
210 ];
211 let norm = [
212 delta.norm_delta[0] as f32 / 63.5,
213 delta.norm_delta[1] as f32 / 63.5,
214 delta.norm_delta[2] as f32 / 63.5,
215 ];
216 (pos, norm)
217}
218
219fn validate_header(header: &MorphSectionHeader) -> Result<(), MorphSectionError> {
220 if header.magic != MAGIC_MRP1 {
221 return Err(MorphSectionError::BadMagic(header.magic));
222 }
223 if header.version != MORPH_SECTION_VERSION {
224 return Err(MorphSectionError::UnsupportedVersion(header.version));
225 }
226 if header.reserved != [0u8; 8] {
227 return Err(MorphSectionError::NonZeroReserved);
228 }
229 if header.target_count == 0
230 || header.target_count as usize > MAX_MORPH_TARGETS
231 || header.vertex_count == 0
232 {
233 return Err(MorphSectionError::InvalidHeaderCounts {
234 target_count: header.target_count,
235 vertex_count: header.vertex_count,
236 });
237 }
238 if !header.max_displacement.is_finite() || header.max_displacement < 0.0 {
239 return Err(MorphSectionError::InvalidMaxDisplacement);
240 }
241 Ok(())
242}
243
244pub fn encode_morph_section(
246 header: &MorphSectionHeader,
247 deltas: &[QuantizedMorphDelta],
248 out: &mut [u8],
249) -> Result<usize, MorphSectionError> {
250 validate_header(header)?;
251 if deltas.len() > MAX_MORPH_DELTAS {
252 return Err(MorphSectionError::TooManyDeltas {
253 count: deltas.len(),
254 max: MAX_MORPH_DELTAS,
255 });
256 }
257 for (index, d) in deltas.iter().enumerate() {
258 if d.target_index as u16 >= header.target_count {
259 return Err(MorphSectionError::DeltaTargetOutOfRange {
260 index,
261 target_index: d.target_index,
262 target_count: header.target_count,
263 });
264 }
265 if d.vertex_index >= header.vertex_count {
266 return Err(MorphSectionError::DeltaVertexOutOfRange {
267 index,
268 vertex_index: d.vertex_index,
269 vertex_count: header.vertex_count,
270 });
271 }
272 }
273
274 let needed = morph_section_encoded_len(deltas.len()).ok_or(MorphSectionError::TooManyDeltas {
275 count: deltas.len(),
276 max: MAX_MORPH_DELTAS,
277 })?;
278 if out.len() < needed {
279 return Err(MorphSectionError::BufferTooSmall {
280 need: needed,
281 have: out.len(),
282 });
283 }
284
285 out[..MORPH_SECTION_HEADER_SIZE].copy_from_slice(bytemuck::bytes_of(header));
286 let mut cursor = MORPH_SECTION_HEADER_SIZE;
287 for d in deltas {
288 out[cursor..cursor + QUANTIZED_MORPH_DELTA_SIZE].copy_from_slice(bytemuck::bytes_of(d));
289 cursor += QUANTIZED_MORPH_DELTA_SIZE;
290 }
291 Ok(needed)
292}
293
294pub fn decode_morph_section_into(
296 payload: &[u8],
297 out_deltas: &mut [QuantizedMorphDelta],
298) -> Result<(MorphSectionHeader, usize), MorphSectionError> {
299 if payload.len() < MORPH_SECTION_HEADER_SIZE {
300 return Err(MorphSectionError::PayloadTooShort {
301 need: MORPH_SECTION_HEADER_SIZE,
302 have: payload.len(),
303 });
304 }
305 let body_len = payload.len() - MORPH_SECTION_HEADER_SIZE;
306 if body_len % QUANTIZED_MORPH_DELTA_SIZE != 0 {
307 return Err(MorphSectionError::PayloadLengthMismatch {
308 payload_len: payload.len(),
309 });
310 }
311 let delta_count = body_len / QUANTIZED_MORPH_DELTA_SIZE;
312 if delta_count > MAX_MORPH_DELTAS {
313 return Err(MorphSectionError::TooManyDeltas {
314 count: delta_count,
315 max: MAX_MORPH_DELTAS,
316 });
317 }
318
319 let header: MorphSectionHeader =
320 bytemuck::pod_read_unaligned(&payload[..MORPH_SECTION_HEADER_SIZE]);
321 validate_header(&header)?;
322
323 if out_deltas.len() < delta_count {
324 return Err(MorphSectionError::BufferTooSmall {
325 need: delta_count,
326 have: out_deltas.len(),
327 });
328 }
329
330 for index in 0..delta_count {
332 let start = MORPH_SECTION_HEADER_SIZE + index * QUANTIZED_MORPH_DELTA_SIZE;
333 let d: QuantizedMorphDelta =
334 bytemuck::pod_read_unaligned(&payload[start..start + QUANTIZED_MORPH_DELTA_SIZE]);
335 if d.target_index as u16 >= header.target_count {
336 return Err(MorphSectionError::DeltaTargetOutOfRange {
337 index,
338 target_index: d.target_index,
339 target_count: header.target_count,
340 });
341 }
342 if d.vertex_index >= header.vertex_count {
343 return Err(MorphSectionError::DeltaVertexOutOfRange {
344 index,
345 vertex_index: d.vertex_index,
346 vertex_count: header.vertex_count,
347 });
348 }
349 }
350 for (index, slot) in out_deltas[..delta_count].iter_mut().enumerate() {
351 let start = MORPH_SECTION_HEADER_SIZE + index * QUANTIZED_MORPH_DELTA_SIZE;
352 *slot = bytemuck::pod_read_unaligned(&payload[start..start + QUANTIZED_MORPH_DELTA_SIZE]);
353 }
354
355 Ok((header, delta_count))
356}
357
358pub fn apply_morph_targets_zero_heap(
360 header: &MorphSectionHeader,
361 deltas: &[QuantizedMorphDelta],
362 weights: &[f32],
363 inout_positions: &mut [[f32; 3]],
364 mut inout_normals: Option<&mut [[f32; 3]]>,
365) -> Result<(), MorphSectionError> {
366 validate_header(header)?;
367 if inout_positions.len() < header.vertex_count as usize {
368 return Err(MorphSectionError::BufferTooSmall {
369 need: header.vertex_count as usize,
370 have: inout_positions.len(),
371 });
372 }
373 if let Some(norms) = inout_normals.as_deref() {
374 if norms.len() < header.vertex_count as usize {
375 return Err(MorphSectionError::BufferTooSmall {
376 need: header.vertex_count as usize,
377 have: norms.len(),
378 });
379 }
380 }
381
382 for (index, d) in deltas.iter().enumerate() {
383 if d.target_index as u16 >= header.target_count {
384 return Err(MorphSectionError::DeltaTargetOutOfRange {
385 index,
386 target_index: d.target_index,
387 target_count: header.target_count,
388 });
389 }
390 if d.vertex_index >= header.vertex_count {
391 return Err(MorphSectionError::DeltaVertexOutOfRange {
392 index,
393 vertex_index: d.vertex_index,
394 vertex_count: header.vertex_count,
395 });
396 }
397 let weight = weights.get(d.target_index as usize).copied().unwrap_or(0.0);
398 if weight.abs() <= 1e-7 {
399 continue;
400 }
401 let (p_delta, n_delta) = dequantize_morph_delta(d, header.max_displacement);
402 let vi = d.vertex_index as usize;
403 inout_positions[vi][0] += p_delta[0] * weight;
404 inout_positions[vi][1] += p_delta[1] * weight;
405 inout_positions[vi][2] += p_delta[2] * weight;
406 if let Some(norms) = inout_normals.as_deref_mut() {
407 norms[vi][0] += n_delta[0] * weight;
408 norms[vi][1] += n_delta[1] * weight;
409 norms[vi][2] += n_delta[2] * weight;
410 }
411 }
412 Ok(())
413}
414
415#[cfg(test)]
416mod tests {
417 use super::*;
418
419 #[test]
420 fn morph_section_encode_decode_and_apply_roundtrips() {
421 let header = MorphSectionHeader {
422 magic: MAGIC_MRP1,
423 version: MORPH_SECTION_VERSION,
424 target_count: 2,
425 vertex_count: 4,
426 flags: FLAG_MORPH_SPARSE | FLAG_MORPH_HAS_NORMALS | FLAG_MORPH_ONTOGENETIC_BIND,
427 max_displacement: 2.0,
428 ontogenetic_bind_mask: 0b0011,
429 reserved: [0u8; 8],
430 };
431
432 let d0 = quantize_morph_delta([1.0, -0.5, 0.25], [0.0, 1.0, 0.0], [0.0; 3], 2.0, 0, 1);
433 let d1 = quantize_morph_delta([0.0, 2.0, -1.0], [0.5, 0.0, -0.5], [0.0; 3], 2.0, 1, 3);
434 let deltas = [d0, d1];
435
436 let mut buf = [0u8; 128];
437 let written = encode_morph_section(&header, &deltas, &mut buf).unwrap();
438 assert_eq!(written, MORPH_SECTION_HEADER_SIZE + 2 * QUANTIZED_MORPH_DELTA_SIZE);
439
440 let mut decoded_deltas = [QuantizedMorphDelta::zeroed(); 4];
441 let (decoded_hdr, count) =
442 decode_morph_section_into(&buf[..written], &mut decoded_deltas).unwrap();
443 assert_eq!(decoded_hdr, header);
444 assert_eq!(count, 2);
445 assert_eq!(&decoded_deltas[..2], &deltas);
446
447 let mut positions = [[0.0f32; 3]; 4];
448 let mut normals = [[0.0f32; 3]; 4];
449 apply_morph_targets_zero_heap(
450 &decoded_hdr,
451 &decoded_deltas[..count],
452 &[0.5, 1.0],
453 &mut positions,
454 Some(&mut normals),
455 )
456 .unwrap();
457
458 assert!((positions[1][0] - 0.5).abs() < 1e-3);
459 assert!((positions[1][1] + 0.25).abs() < 1e-3);
460 assert!((positions[3][1] - 2.0).abs() < 1e-3);
461 assert!((normals[1][1] - 0.5).abs() < 2e-2);
462 }
463
464 #[test]
465 fn morph_section_rejects_out_of_range_indices_and_bad_magic() {
466 let mut bad_hdr = MorphSectionHeader {
467 magic: *b"XXXX",
468 version: 1,
469 target_count: 1,
470 vertex_count: 2,
471 flags: FLAG_MORPH_SPARSE,
472 max_displacement: 1.0,
473 ontogenetic_bind_mask: 0,
474 reserved: [0u8; 8],
475 };
476 let mut buf = [0u8; 64];
477 assert!(matches!(
478 encode_morph_section(&bad_hdr, &[], &mut buf),
479 Err(MorphSectionError::BadMagic(_))
480 ));
481
482 bad_hdr.magic = MAGIC_MRP1;
483 let bad_delta = quantize_morph_delta([0.1, 0.0, 0.0], [0.0; 3], [0.0; 3], 1.0, 0, 99);
484 assert!(matches!(
485 encode_morph_section(&bad_hdr, &[bad_delta], &mut buf),
486 Err(MorphSectionError::DeltaVertexOutOfRange { .. })
487 ));
488 }
489}