Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_asset/
tracks.rs

1//! Version 6 `.psxanim` clips: per-joint keyed tracks.
2//!
3//! The layout is documented on [`psxed_format::animation::tracks`]. A clip holds
4//! one rotation track (smallest-three quaternion keys) and one translation track
5//! (variable-bit offsets) per joint. Every track is `segments + 1` evenly spaced
6//! keys over the clip, with at most seven distinct segment counts per clip, so a
7//! sample maps its playback position onto every rate once and each joint then
8//! only indexes.
9//!
10//! Decoding is integer only: Q12 quaternion components, a 513 entry square root
11//! table for the omitted component, Q8 interpolation, one renormalising step and
12//! the usual quaternion to matrix products. The cooker calls the same functions
13//! to prove its error budget, so what it measures is what ships.
14
15use core::ptr;
16
17use psx_gte::math::Vec3I32;
18use psxed_format::animation::tracks as fmt;
19
20use crate::{JointPose, ParseError};
21
22/// `round(sqrt(n))` for the table builder.
23const fn isqrt_round(n: u32) -> u32 {
24    let mut lo = 0u32;
25    let mut hi = 4200u32;
26    while lo < hi {
27        let mid = (lo + hi).div_ceil(2);
28        if mid * mid <= n {
29            lo = mid;
30        } else {
31            hi = mid - 1;
32        }
33    }
34    if n - lo * lo > lo {
35        lo + 1
36    } else {
37        lo
38    }
39}
40
41const fn build_sqrt_table() -> [u16; 514] {
42    let mut table = [0u16; 514];
43    let mut i = 0usize;
44    while i <= 513 {
45        table[i] = isqrt_round((i as u32) << 15) as u16;
46        i += 1;
47    }
48    table
49}
50
51/// `round(sqrt(index << 15))`: the Q12 square root of a Q24 value sampled every
52/// 2^15, one entry past the top so the interpolation of an exact 2^24 (the
53/// identity rotation) has a neighbour. The omitted quaternion component is at least one half, so the argument
54/// stays far from the steep start of the curve and one linear step is exact to
55/// well under a Q12 unit.
56pub const SQRT_TABLE: [u16; 514] = build_sqrt_table();
57
58const MUL: [i32; 3] = [
59    fmt::component_mul(0),
60    fmt::component_mul(1),
61    fmt::component_mul(2),
62];
63
64const RATE_TABLE_OFFSET: usize = psxed_format::AssetHeader::SIZE + 8;
65const DESCRIPTORS_OFFSET: usize = RATE_TABLE_OFFSET + fmt::RATE_TABLE_SIZE;
66
67/// Positions of one playback sample on every rate of a clip.
68///
69/// Entry [`fmt::RATE_CONSTANT`] is always `(0, 0)`, which is how a constant
70/// track reads its only key.
71#[derive(Copy, Clone, Debug, PartialEq, Eq)]
72pub struct TrackPos {
73    idx: [u16; 8],
74    frac: [u16; 8],
75}
76
77impl TrackPos {
78    /// All tracks at their first key.
79    pub const ZERO: Self = Self {
80        idx: [0; 8],
81        frac: [0; 8],
82    };
83
84    /// Key index and Q8 fraction (`0..=256`) of rate `rate`.
85    pub fn rate(&self, rate: usize) -> (u16, u16) {
86        (self.idx[rate & 7], self.frac[rate & 7])
87    }
88}
89
90/// A decoded rotation key: Q12 `[x, y, z, w]` and the omitted component index.
91#[derive(Copy, Clone, Debug, PartialEq, Eq)]
92pub struct RotKey {
93    /// Q12 quaternion components, x y z w.
94    pub q: [i32; 4],
95    /// Index of the component the key omitted.
96    pub omitted: u8,
97}
98
99/// Validated view of a v6 payload. Built only by [`validate`], which proves
100/// every unchecked read in this module stays inside `blob`.
101#[derive(Copy, Clone, Debug)]
102pub(crate) struct Tracks {
103    blob: *const u8,
104    joint_count: u16,
105    key_area: usize,
106    len: usize,
107    translation_shift: u8,
108}
109
110// SAFETY: `Tracks` is only a pointer to immutable cooked data owned by the
111// caller's `'a` slice; it is never written through.
112unsafe impl Send for Tracks {}
113// SAFETY: as above, shared reads of immutable data.
114unsafe impl Sync for Tracks {}
115
116#[inline(always)]
117fn le_u16(blob: &[u8], at: usize) -> u16 {
118    u16::from_le_bytes([blob[at], blob[at + 1]])
119}
120
121/// Check a v6 blob completely. On success every key read the decoder can make
122/// lies inside `blob`.
123pub(crate) fn validate(
124    blob: &[u8],
125    joint_count: u16,
126    frame_count: u16,
127    translation_shift: u8,
128) -> Result<Tracks, ParseError> {
129    let bad = ParseError::InvalidAnimationLayout;
130    if !(2..=fmt::MAX_FRAMES).contains(&frame_count) || translation_shift > 8 {
131        return Err(bad);
132    }
133    let joints = joint_count as usize;
134    let key_area = joints
135        .checked_mul(fmt::DESCRIPTOR_SIZE)
136        .and_then(|d| d.checked_add(DESCRIPTORS_OFFSET))
137        .ok_or(ParseError::TableOverflow)?;
138    if blob.len() < key_area + fmt::SLACK_BYTES {
139        return Err(ParseError::Truncated);
140    }
141    let area_len = blob.len() - fmt::SLACK_BYTES - key_area;
142    if area_len > fmt::MAX_KEY_AREA {
143        return Err(bad);
144    }
145    let rate_count = blob[RATE_TABLE_OFFSET] as usize;
146    if rate_count == 0 || rate_count > fmt::MAX_RATES {
147        return Err(bad);
148    }
149    let mut segments = [0usize; 8];
150    for (r, slot) in segments.iter_mut().enumerate().take(rate_count) {
151        let s = le_u16(blob, RATE_TABLE_OFFSET + 2 + r * 2) as usize;
152        if s == 0 || s > frame_count as usize - 1 {
153            return Err(bad);
154        }
155        *slot = s;
156    }
157    let keys_for = |rate: u8| -> Option<usize> {
158        if rate == fmt::RATE_CONSTANT {
159            Some(1)
160        } else if (rate as usize) < rate_count {
161            Some(segments[rate as usize] + 1)
162        } else {
163            None
164        }
165    };
166    // Every read is a u32 at the key start plus a u16 four bytes on.
167    let fits = |off: usize, keys: usize, stride: usize| -> bool {
168        let last = off + (keys - 1) * stride;
169        let end = off + keys * stride;
170        end <= area_len && last + 6 <= area_len + fmt::SLACK_BYTES
171    };
172    for j in 0..joints {
173        let d = DESCRIPTORS_OFFSET + j * fmt::DESCRIPTOR_SIZE;
174        let rot_ctl = blob[d];
175        let trans_ctl = blob[d + 1];
176        let axis = le_u16(blob, d + 2);
177        let rot_off = le_u16(blob, d + 4) as usize;
178        let trans_off = le_u16(blob, d + 6) as usize;
179        let key_bytes = blob[d + 14] as usize;
180        let size = (rot_ctl >> 3) & 3;
181        if rot_ctl >> 5 != 0 || size > 2 || trans_ctl >> 7 != 0 || axis >> 15 != 0 {
182            return Err(bad);
183        }
184        let rot_keys = keys_for(rot_ctl & 7).ok_or(bad)?;
185        let trans_keys = keys_for(trans_ctl & 7).ok_or(bad)?;
186        let (bx, by, bz) = (
187            (axis & 31) as usize,
188            ((axis >> 5) & 31) as usize,
189            ((axis >> 10) & 31) as usize,
190        );
191        // The axis extraction needs b0 + b1 < 32 and each field below 32 bits.
192        if bx > 15 || by > 15 || bz > 15 || key_bytes != (bx + by + bz).div_ceil(8) {
193            return Err(bad);
194        }
195        if !fits(rot_off, rot_keys, fmt::rotation_key_bytes(size)) {
196            return Err(bad);
197        }
198        if !fits(trans_off, trans_keys, key_bytes) {
199            return Err(bad);
200        }
201    }
202    Ok(Tracks {
203        blob: blob.as_ptr(),
204        joint_count,
205        key_area,
206        len: blob.len(),
207        translation_shift,
208    })
209}
210
211/// Map a playback position (Q8 source frames in `0..(frame_count - 1) << 8`) to
212/// a key index and Q8 fraction on every rate.
213pub(crate) fn track_pos(blob: &[u8], pos_q8: u32) -> TrackPos {
214    let mut out = TrackPos::ZERO;
215    let rate_count = blob[RATE_TABLE_OFFSET] as usize;
216    let mut r = 0;
217    while r < rate_count {
218        let seg = u32::from(le_u16(blob, RATE_TABLE_OFFSET + 2 + r * 2));
219        let factor = u32::from(le_u16(blob, RATE_TABLE_OFFSET + 16 + r * 2));
220        // pos_q8 < 2^16 and factor <= 2^15 keep the product inside u32.
221        let sp = (pos_q8 * factor) >> 15;
222        let i = sp >> 8;
223        if i >= seg {
224            out.idx[r] = (seg - 1) as u16;
225            out.frac[r] = 256;
226        } else {
227            out.idx[r] = i as u16;
228            out.frac[r] = (sp & 255) as u16;
229        }
230        r += 1;
231    }
232    out
233}
234
235#[inline(always)]
236unsafe fn read_u32(p: *const u8) -> u32 {
237    // SAFETY: the caller keeps `p..p + 4` inside the validated blob.
238    u32::from_le(unsafe { ptr::read_unaligned(p.cast::<u32>()) })
239}
240
241#[inline(always)]
242unsafe fn read_u16(p: *const u8) -> u32 {
243    // SAFETY: the caller keeps `p..p + 2` inside the validated blob.
244    u32::from(u16::from_le(unsafe {
245        ptr::read_unaligned(p.cast::<u16>())
246    }))
247}
248
249/// Decode one rotation key. Needs six readable bytes at `p`.
250///
251/// # Safety
252/// `p..p + 6` must be readable.
253#[inline(always)]
254unsafe fn decode_rot(p: *const u8, size: u32) -> RotKey {
255    // SAFETY: forwarded from the caller.
256    let lo = unsafe { read_u32(p) };
257    // SAFETY: forwarded from the caller.
258    let hi = unsafe { read_u16(p.add(4)) };
259    let bits = 10 + 2 * size;
260    let mask = (1u32 << bits) - 1;
261    let sh1 = 2 + bits;
262    let sh2 = 2 + 2 * bits;
263    let sign = 32 - bits;
264    let c0 = (lo >> 2) & mask;
265    let c1 = (lo >> sh1) & mask;
266    let c2 = ((lo >> sh2) | (hi << (32 - sh2))) & mask;
267    let mul = MUL[size as usize];
268    let dq = |c: u32| -> i32 {
269        let signed = ((c << sign) as i32) >> sign;
270        (signed * mul + (1 << 13)) >> 14
271    };
272    let (a, b, c) = (dq(c0), dq(c1), dq(c2));
273    let r = (1i32 << 24) - (a * a + b * b + c * c);
274    let r = if r < 0 { 0 } else { r };
275    let i = (r >> 15) as usize;
276    let t0 = i32::from(SQRT_TABLE[i]);
277    let t1 = i32::from(SQRT_TABLE[i + 1]);
278    let w = t0 + (((t1 - t0) * (r & 0x7fff)) >> 15);
279    let omitted = (lo & 3) as u8;
280    let q = match omitted {
281        0 => [w, a, b, c],
282        1 => [a, w, b, c],
283        2 => [a, b, w, c],
284        _ => [a, b, c, w],
285    };
286    RotKey { q, omitted }
287}
288
289/// Matrix of the quaternion `a` blended towards `b` by `frac / 256`.
290#[inline(always)]
291fn rotation_matrix(a: RotKey, b: Option<RotKey>, frac: i32) -> [[i16; 3]; 3] {
292    let mut q = a.q;
293    let mut renorm = false;
294    if let Some(b) = b {
295        let mut bq = b.q;
296        // Canonical keys keep their largest component positive, so two keys that
297        // agree on it can only be on one hemisphere unless they are far apart.
298        // When it differs, check the dot product and take the short way round.
299        if a.omitted != b.omitted
300            && a.q[0] * bq[0] + a.q[1] * bq[1] + a.q[2] * bq[2] + a.q[3] * bq[3] < 0
301        {
302            bq = [-bq[0], -bq[1], -bq[2], -bq[3]];
303        }
304        q = [
305            a.q[0] + (((bq[0] - a.q[0]) * frac) >> 8),
306            a.q[1] + (((bq[1] - a.q[1]) * frac) >> 8),
307            a.q[2] + (((bq[2] - a.q[2]) * frac) >> 8),
308            a.q[3] + (((bq[3] - a.q[3]) * frac) >> 8),
309        ];
310        renorm = frac != 0 && frac != 256;
311    }
312    quat_to_matrix(q, renorm)
313}
314
315#[inline(always)]
316fn quat_to_matrix(q: [i32; 4], renorm: bool) -> [[i16; 3]; 3] {
317    let [mut x, mut y, mut z, mut w] = q;
318    if renorm {
319        // One Newton-style step of the inverse square root around unit length.
320        let n = (x * x + y * y + z * z + w * w + 2048) >> 12;
321        let e = (4096 - n).clamp(-4096, 4096);
322        let r = 4096 + (e >> 1) + ((3 * e * e) >> 15);
323        x = (x * r + 2048) >> 12;
324        y = (y * r + 2048) >> 12;
325        z = (z * r + 2048) >> 12;
326        w = (w * r + 2048) >> 12;
327    }
328    let m2 = |a: i32, b: i32| (a * b + 1024) >> 11;
329    let (xx, yy, zz) = (m2(x, x), m2(y, y), m2(z, z));
330    let (xy, xz, yz) = (m2(x, y), m2(x, z), m2(y, z));
331    let (wx, wy, wz) = (m2(w, x), m2(w, y), m2(w, z));
332    [
333        [
334            (4096 - (yy + zz)) as i16,
335            (xy - wz) as i16,
336            (xz + wy) as i16,
337        ],
338        [
339            (xy + wz) as i16,
340            (4096 - (xx + zz)) as i16,
341            (yz - wx) as i16,
342        ],
343        [
344            (xz - wy) as i16,
345            (yz + wx) as i16,
346            (4096 - (xx + yy)) as i16,
347        ],
348    ]
349}
350
351/// Decode a translation key into three axis codes.
352///
353/// # Safety
354/// `p..p + 6` must be readable.
355#[inline(always)]
356unsafe fn decode_trans_codes(p: *const u8, axis: u32) -> [i32; 3] {
357    // SAFETY: forwarded from the caller.
358    let lo = unsafe { read_u32(p) };
359    // SAFETY: forwarded from the caller.
360    let hi = unsafe { read_u16(p.add(4)) };
361    let (b0, b1, b2) = (axis & 31, (axis >> 5) & 31, (axis >> 10) & 31);
362    let (m0, m1, m2) = ((1u32 << b0) - 1, (1u32 << b1) - 1, (1u32 << b2) - 1);
363    let sh = b0 + b1;
364    let c0 = lo & m0;
365    let c1 = (lo >> b0) & m1;
366    // `<< (31 - sh) << 1` keeps the shift below 32 even when sh == 0.
367    let c2 = ((lo >> sh) | ((hi << (31 - sh)) << 1)) & m2;
368    [c0 as i32, c1 as i32, c2 as i32]
369}
370
371/// Evaluate the pose of joint `joint` at the positions in `pos`.
372///
373/// # Safety
374/// `tracks` must come from [`validate`] and `joint < joint_count`.
375#[inline]
376pub(crate) unsafe fn joint_pose(tracks: &Tracks, joint: usize, pos: &TrackPos) -> JointPose {
377    debug_assert!(joint < tracks.joint_count as usize);
378    // SAFETY: `joint < joint_count`, so the 16 byte descriptor is inside the
379    // blob `validate` measured.
380    let d = unsafe {
381        tracks
382            .blob
383            .add(DESCRIPTORS_OFFSET + joint * fmt::DESCRIPTOR_SIZE)
384    };
385    // SAFETY: the descriptor is 16 readable bytes.
386    let w0 = unsafe { read_u32(d) };
387    // SAFETY: as above.
388    let w1 = unsafe { read_u32(d.add(4)) };
389    // SAFETY: as above.
390    let w2 = unsafe { read_u32(d.add(8)) };
391    // SAFETY: as above.
392    let w3 = unsafe { read_u32(d.add(12)) };
393    let rot_rate = (w0 & 7) as usize;
394    let size = (w0 >> 3) & 3;
395    let trans_rate = ((w0 >> 8) & 7) as usize;
396    let step = (w0 >> 11) & 15;
397    let axis = w0 >> 16;
398    let rot_off = (w1 & 0xffff) as usize;
399    let trans_off = (w1 >> 16) as usize;
400    let key_bytes = (w3 >> 16) & 0xff;
401    // SAFETY: `validate` proved offsets, key counts and strides stay inside the
402    // key area plus its slack, for every index `track_pos` can produce.
403    let area = unsafe { tracks.blob.add(tracks.key_area) };
404
405    let (ri, rf) = (pos.idx[rot_rate] as usize, i32::from(pos.frac[rot_rate]));
406    let stride = fmt::rotation_key_bytes(size as u8);
407    // Debug builds (the corruption tests) check every window against the blob.
408    debug_assert!(
409        tracks.key_area + rot_off + (ri + usize::from(rf != 0)) * stride + 6 <= tracks.len
410    );
411    // SAFETY: key `ri` of the rotation track starts inside the validated range.
412    let ka = unsafe { decode_rot(area.add(rot_off + ri * stride), size) };
413    let matrix = if rf == 0 {
414        rotation_matrix(ka, None, 0)
415    } else {
416        // SAFETY: a non zero fraction implies `ri + 1` is a key of the track.
417        let kb = unsafe { decode_rot(area.add(rot_off + (ri + 1) * stride), size) };
418        rotation_matrix(ka, Some(kb), rf)
419    };
420
421    let (ti, tf) = (
422        pos.idx[trans_rate] as usize,
423        i32::from(pos.frac[trans_rate]),
424    );
425    let min = [
426        (w2 as i16) as i32,
427        ((w2 >> 16) as i16) as i32,
428        (w3 as i16) as i32,
429    ];
430    let shift = u32::from(tracks.translation_shift);
431    let kb = key_bytes as usize;
432    debug_assert!(tracks.key_area + trans_off + (ti + usize::from(tf != 0)) * kb + 6 <= tracks.len);
433    // SAFETY: as for the rotation track.
434    let ca = unsafe { decode_trans_codes(area.add(trans_off + ti * kb), axis) };
435    let mut t = [
436        min[0] + (ca[0] << step),
437        min[1] + (ca[1] << step),
438        min[2] + (ca[2] << step),
439    ];
440    if tf != 0 {
441        // SAFETY: a non zero fraction implies `ti + 1` is a key of the track.
442        let cb = unsafe { decode_trans_codes(area.add(trans_off + (ti + 1) * kb), axis) };
443        for a in 0..3 {
444            let b = min[a] + (cb[a] << step);
445            t[a] += ((b - t[a]) * tf) >> 8;
446        }
447    }
448    JointPose {
449        matrix,
450        translation: Vec3I32::new(t[0] << shift, t[1] << shift, t[2] << shift),
451    }
452}
453
454/// Safe single-key helpers the cooker uses to search and verify tracks with the
455/// exact decoder.
456pub mod host {
457    use super::*;
458
459    /// Decode a rotation key from the first six bytes of `key`.
460    pub fn decode_rotation_key(key: &[u8; 6], size_code: u8) -> RotKey {
461        // SAFETY: `key` is exactly six readable bytes.
462        unsafe { decode_rot(key.as_ptr(), u32::from(size_code.min(2))) }
463    }
464
465    /// Matrix of `a` blended towards `b` by `frac / 256` (`0..=256`).
466    pub fn blend_rotation(a: RotKey, b: Option<RotKey>, frac: i32) -> [[i16; 3]; 3] {
467        rotation_matrix(a, b, frac)
468    }
469
470    /// Decode a translation key's three axis codes from six bytes.
471    pub fn decode_translation_codes(key: &[u8; 6], axis_bits: u16) -> [i32; 3] {
472        // SAFETY: `key` is exactly six readable bytes.
473        unsafe { decode_trans_codes(key.as_ptr(), u32::from(axis_bits)) }
474    }
475
476    /// Key index and fraction of a playback position, as the sampler computes
477    /// them for a clip of `frame_count` frames with `segments` segments.
478    pub fn locate(segments: u16, frame_count: u16, pos_q8: u32) -> (u16, u16) {
479        let factor = ((u32::from(segments) << 15) + (u32::from(frame_count) - 1) / 2)
480            / (u32::from(frame_count) - 1);
481        let sp = (pos_q8 * factor) >> 15;
482        let i = sp >> 8;
483        if i >= u32::from(segments) {
484            (segments - 1, 256)
485        } else {
486            (i as u16, (sp & 255) as u16)
487        }
488    }
489
490    /// The Q15 factor stored in the rate table for a segment count.
491    pub fn rate_factor(segments: u16, frame_count: u16) -> u16 {
492        (((u32::from(segments) << 15) + (u32::from(frame_count) - 1) / 2)
493            / (u32::from(frame_count) - 1)) as u16
494    }
495}