plasma-prp 0.1.0

Read, write, inspect, and manipulate Plasma engine PRP files used by Myst Online: Uru Live
Documentation
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! Animation evaluator — interpolates keyframes to produce bone transforms.
//!
//! Evaluates controllers per-bone per-frame to produce 4x4 transform matrices.
//! Handles both animated bones (plMatrixControllerChannel with keyframes) and
//! static bones (plMatrixConstant with a fixed pose).
//!
//! C++ ref: plAGAnimInstance.cpp, plMatrixControllerChannel.cpp (Value method),
//!          plController.cpp (Interp methods), hsAffineParts.cpp (ComposeMatrix)

use std::collections::HashMap;

use super::ag_anim::{AffineParts, AGAnimData, ATCAnimData, ChannelData};
use super::controller::{Controller, LeafController, TMController, CompoundController};
use super::keys::{KeyFrame, KeyType, decompress_quat32, decompress_quat64};

/// Per-bone channel data for evaluation.
#[derive(Debug, Clone)]
pub enum BoneChannel {
    /// Animated bone — controller with keyframes + initial rest pose.
    Animated {
        controller: Controller,
        initial_pose: AffineParts,
    },
    /// Static bone — constant transform, no animation.
    Constant {
        pose: AffineParts,
    },
}

/// A loaded animation clip ready for evaluation.
///
/// Maps bone names to their channel data, extracted from
/// plATCAnim applicator/channel data.
#[derive(Debug, Clone)]
pub struct AnimClip {
    pub name: String,
    pub start: f32,
    pub end: f32,
    pub do_loop: bool,
    pub loop_start: f32,
    pub loop_end: f32,
    /// Bone name → channel data (animated or constant).
    pub bone_channels: HashMap<String, BoneChannel>,
}

/// Extract bone channels from an applicator list.
fn extract_bone_channels(applicators: &[super::ag_anim::AnimApplicator]) -> HashMap<String, BoneChannel> {
    let mut bone_channels = HashMap::new();

    for app in applicators {
        if !app.enabled { continue; }

        // Use the applicator's channel_name as the bone name (target).
        // The channel's own name (channel_name_from_channel) is typically empty
        // or matches — prefer the applicator's name.
        let bone_name = if !app.channel_name.is_empty() {
            &app.channel_name
        } else if !app.channel_name_from_channel.is_empty() {
            &app.channel_name_from_channel
        } else {
            continue;
        };

        match &app.channel_data {
            ChannelData::MatrixController { controller: Some(ctrl), initial_pose } => {
                bone_channels.insert(bone_name.clone(), BoneChannel::Animated {
                    controller: ctrl.clone(),
                    initial_pose: initial_pose.clone(),
                });
            }
            ChannelData::MatrixController { controller: None, initial_pose } => {
                // Controller is null — treat as constant with the initial pose
                bone_channels.insert(bone_name.clone(), BoneChannel::Constant {
                    pose: initial_pose.clone(),
                });
            }
            ChannelData::MatrixConstant { pose } => {
                bone_channels.insert(bone_name.clone(), BoneChannel::Constant {
                    pose: pose.clone(),
                });
            }
            // Scalar, point, quat channels are not bone transforms — skip
            _ => {}
        }
    }

    bone_channels
}

impl AnimClip {
    /// Build from parsed ATCAnim data.
    pub fn from_atc_anim(anim: &ATCAnimData) -> Self {
        Self {
            name: anim.base.name.clone(),
            start: anim.base.start,
            end: anim.base.end,
            do_loop: anim.do_loop,
            loop_start: anim.loop_start,
            loop_end: anim.loop_end,
            bone_channels: extract_bone_channels(&anim.base.applicators),
        }
    }

    /// Build from base AGAnimData (no ATCAnim loop/ease info — defaults to looping).
    pub fn from_ag_anim(anim: &AGAnimData, do_loop: bool) -> Self {
        Self {
            name: anim.name.clone(),
            start: anim.start,
            end: anim.end,
            do_loop,
            loop_start: anim.start,
            loop_end: anim.end,
            bone_channels: extract_bone_channels(&anim.applicators),
        }
    }

    /// Duration of this animation clip.
    pub fn duration(&self) -> f32 {
        self.end - self.start
    }

    /// Count of animated (non-constant) bone channels.
    pub fn animated_bone_count(&self) -> usize {
        self.bone_channels.values().filter(|ch| matches!(ch, BoneChannel::Animated { .. })).count()
    }
}

/// Evaluate a bone channel at a given time to produce a 4x4 transform matrix.
///
/// For animated channels: evaluates the controller using initial_pose as fallback
/// for absent sub-controllers (matching C++ plCompoundController::Interp which
/// modifies existing fAP in-place, preserving initial values for absent controllers).
/// For constant channels: composes the static pose into a matrix.
///
/// C++ ref: plMatrixControllerChannel::Value (plMatrixChannel.cpp:525-561)
pub fn evaluate_bone_channel(channel: &BoneChannel, time: f32) -> [f32; 16] {
    match channel {
        BoneChannel::Animated { controller, initial_pose } => {
            evaluate_controller_with_initial(controller, time, initial_pose)
        }
        BoneChannel::Constant { pose } => {
            compose_affine_parts(pose)
        }
    }
}

/// Evaluate a controller at a given time, using initial AffineParts as fallback.
///
/// C++ ref: plCompoundController::Interp modifies existing fAP in-place.
/// If a sub-controller (X/Y/Z) is absent, the initial_pose value is preserved.
fn evaluate_controller_with_initial(ctrl: &Controller, time: f32, initial: &AffineParts) -> [f32; 16] {
    match ctrl {
        Controller::TM(tm) => evaluate_tm_controller(tm, time),
        Controller::Compound(compound) => evaluate_compound_with_initial(compound, time, initial),
        Controller::Leaf(leaf) => {
            match leaf.key_type {
                KeyType::Matrix44 => evaluate_leaf_matrix44(leaf, time),
                KeyType::Quat | KeyType::CompressedQuat32 | KeyType::CompressedQuat64 => {
                    let quat = evaluate_leaf_quat(leaf, time);
                    quat_to_matrix(&quat)
                }
                _ => identity_matrix(),
            }
        }
    }
}

/// Evaluate a controller at a given time to produce a 4x4 transform matrix.
/// Uses zero/identity defaults (for non-bone contexts).
pub fn evaluate_controller(ctrl: &Controller, time: f32) -> [f32; 16] {
    let default_ap = AffineParts {
        translation: [0.0, 0.0, 0.0],
        rotation: [0.0, 0.0, 0.0, 1.0],
        stretch_rotation: [0.0, 0.0, 0.0, 1.0],
        scale: [1.0, 1.0, 1.0],
        det_sign: 1.0,
    };
    evaluate_controller_with_initial(ctrl, time, &default_ap)
}

/// Evaluate a compound controller as hsAffineParts → matrix, with initial pose fallback.
///
/// C++ ref: plCompoundController::Interp(float, hsAffineParts*) in plController.cpp:817-833
/// The C++ code modifies the existing hsAffineParts in-place. If a sub-controller is
/// absent, the initial value is preserved.
fn evaluate_compound_with_initial(compound: &CompoundController, time: f32, initial: &AffineParts) -> [f32; 16] {
    // X → translation (Point3) — fallback to initial_pose.translation
    let pos = compound.x_controller.as_ref()
        .map(|c| evaluate_position(c, time))
        .unwrap_or(initial.translation);

    // Y → rotation (Quaternion) — fallback to initial_pose.rotation
    let quat = compound.y_controller.as_ref()
        .map(|c| evaluate_rotation(c, time))
        .unwrap_or(initial.rotation);

    // Z → scale — fallback to initial_pose scale+stretch_rotation
    let (scale, stretch_rot) = compound.z_controller.as_ref()
        .map(|c| evaluate_scale_with_stretch(c, time))
        .unwrap_or((initial.scale, initial.stretch_rotation));

    let det_sign = initial.det_sign;

    compose_full_affine(&pos, &quat, &stretch_rot, &scale, det_sign)
}

/// Compose hsAffineParts into a row-major 4x4 matrix.
/// Full formula: M = T × F × R(Q) × R(U) × Scale(K) × R(U)^T
/// C++ ref: hsAffineParts::ComposeMatrix (hsAffineParts.cpp:124-166)
pub fn compose_affine_parts(ap: &AffineParts) -> [f32; 16] {
    compose_full_affine(&ap.translation, &ap.rotation, &ap.stretch_rotation, &ap.scale, ap.det_sign)
}

/// Full affine composition: M = T × F × R(Q) × R(U) × Scale(K) × R(U)^T
/// C++ ref: hsAffineParts::ComposeMatrix (hsAffineParts.cpp:124-166)
fn compose_full_affine(pos: &[f32; 3], rotation: &[f32; 4], stretch_rot: &[f32; 4], scale: &[f32; 3], det_sign: f32) -> [f32; 16] {
    use crate::core::transform::mat44_multiply;

    // Check if stretch rotation is identity (most common case — skip extra work)
    let u_is_identity = (stretch_rot[0].abs() < 1e-6)
        && (stretch_rot[1].abs() < 1e-6)
        && (stretch_rot[2].abs() < 1e-6)
        && ((stretch_rot[3] - 1.0).abs() < 1e-6 || (stretch_rot[3] + 1.0).abs() < 1e-6);

    let f = if det_sign < 0.0 { -1.0f32 } else { 1.0f32 };

    if u_is_identity {
        // Simplified: M = T × F × R(Q) × Scale(K)
        let rot = quat_to_matrix(rotation);
        [
            rot[0] * scale[0] * f,  rot[1] * scale[1] * f,  rot[2] * scale[2] * f,  pos[0],
            rot[4] * scale[0] * f,  rot[5] * scale[1] * f,  rot[6] * scale[2] * f,  pos[1],
            rot[8] * scale[0] * f,  rot[9] * scale[1] * f,  rot[10] * scale[2] * f, pos[2],
            0.0,                    0.0,                    0.0,                     1.0,
        ]
    } else {
        // Full: M = T × F × R(Q) × R(U) × Scale(K) × R(U)^T
        // Step 1: K × U^T  (scale, then inverse stretch rotation)
        let u_inv = [stretch_rot[0], stretch_rot[1], stretch_rot[2], -stretch_rot[3]]; // conjugate = inverse for unit quat
        let ut_mat = quat_to_matrix(&u_inv);
        let k_ut = [
            ut_mat[0] * scale[0],  ut_mat[1] * scale[0],  ut_mat[2] * scale[0],  0.0,
            ut_mat[4] * scale[1],  ut_mat[5] * scale[1],  ut_mat[6] * scale[1],  0.0,
            ut_mat[8] * scale[2],  ut_mat[9] * scale[2],  ut_mat[10] * scale[2], 0.0,
            0.0,                   0.0,                   0.0,                    1.0,
        ];

        // Step 2: U × (K × U^T)
        let u_mat = quat_to_matrix(stretch_rot);
        let u_k_ut = mat44_multiply(&u_mat, &k_ut);

        // Step 3: R(Q) × U × K × U^T
        let r_mat = quat_to_matrix(rotation);
        let r_u_k_ut = mat44_multiply(&r_mat, &u_k_ut);

        // Step 4: Apply flip (F) and translation (T)
        [
            r_u_k_ut[0] * f,  r_u_k_ut[1] * f,  r_u_k_ut[2] * f,  pos[0],
            r_u_k_ut[4] * f,  r_u_k_ut[5] * f,  r_u_k_ut[6] * f,  pos[1],
            r_u_k_ut[8] * f,  r_u_k_ut[9] * f,  r_u_k_ut[10] * f, pos[2],
            0.0,               0.0,               0.0,               1.0,
        ]
    }
}

// ============================================================================
// Controller evaluation
// ============================================================================

/// Evaluate a TM (Transform) controller at a given time.
/// C++ ref: plTMController::Interp → hsAffineParts::ComposeMatrix
fn evaluate_tm_controller(tm: &TMController, time: f32) -> [f32; 16] {
    let pos = tm.pos_controller.as_ref()
        .map(|c| evaluate_position(c, time))
        .unwrap_or([0.0, 0.0, 0.0]);

    let quat = tm.rot_controller.as_ref()
        .map(|c| evaluate_rotation(c, time))
        .unwrap_or([0.0, 0.0, 0.0, 1.0]);

    let scale = tm.scale_controller.as_ref()
        .map(|c| evaluate_scale(c, time))
        .unwrap_or([1.0, 1.0, 1.0]);

    compose_trs(&pos, &quat, &scale)
}

fn evaluate_position(ctrl: &Controller, time: f32) -> [f32; 3] {
    match ctrl {
        Controller::Leaf(leaf) => evaluate_leaf_point3(leaf, time),
        Controller::Compound(compound) => {
            let x = compound.x_controller.as_ref()
                .map(|c| evaluate_scalar(c, time)).unwrap_or(0.0);
            let y = compound.y_controller.as_ref()
                .map(|c| evaluate_scalar(c, time)).unwrap_or(0.0);
            let z = compound.z_controller.as_ref()
                .map(|c| evaluate_scalar(c, time)).unwrap_or(0.0);
            [x, y, z]
        }
        Controller::TM(_) => [0.0, 0.0, 0.0],
    }
}

fn evaluate_rotation(ctrl: &Controller, time: f32) -> [f32; 4] {
    match ctrl {
        Controller::Leaf(leaf) => evaluate_leaf_quat(leaf, time),
        Controller::Compound(compound) => {
            // A compound rotation controller has X/Y/Z sub-controllers
            // for individual quaternion components or Euler angles.
            // In Plasma's plCompoundController::Interp(float, hsQuat*),
            // it calls fXController->Interp(time, &result), which treats
            // the sub-controllers as scalar components. However, the Y
            // sub-controller of a top-level compound IS a leaf quat.
            // If sub-controllers are scalars, treat as Euler.
            let x = compound.x_controller.as_ref()
                .map(|c| evaluate_scalar(c, time)).unwrap_or(0.0);
            let y = compound.y_controller.as_ref()
                .map(|c| evaluate_scalar(c, time)).unwrap_or(0.0);
            let z = compound.z_controller.as_ref()
                .map(|c| evaluate_scalar(c, time)).unwrap_or(0.0);
            euler_to_quat(x, y, z)
        }
        Controller::TM(_) => [0.0, 0.0, 0.0, 1.0],
    }
}

fn evaluate_scale(ctrl: &Controller, time: f32) -> [f32; 3] {
    evaluate_scale_with_stretch(ctrl, time).0
}

/// Evaluate scale controller returning both scale factors (K) and stretch rotation (U).
/// C++ ref: plCompoundController::Interp — Z controller → fK + fU
fn evaluate_scale_with_stretch(ctrl: &Controller, time: f32) -> ([f32; 3], [f32; 4]) {
    match ctrl {
        Controller::Leaf(leaf) => {
            match leaf.key_type {
                KeyType::Scale | KeyType::BezScale => evaluate_leaf_scale_with_stretch(leaf, time),
                KeyType::Point3 | KeyType::BezPoint3 => {
                    (evaluate_leaf_point3(leaf, time), [0.0, 0.0, 0.0, 1.0])
                }
                KeyType::Scalar | KeyType::BezScalar => {
                    let s = evaluate_leaf_scalar(leaf, time);
                    ([s, s, s], [0.0, 0.0, 0.0, 1.0])
                }
                _ => ([1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]),
            }
        }
        Controller::Compound(compound) => {
            let x = compound.x_controller.as_ref()
                .map(|c| evaluate_scalar(c, time)).unwrap_or(1.0);
            let y = compound.y_controller.as_ref()
                .map(|c| evaluate_scalar(c, time)).unwrap_or(1.0);
            let z = compound.z_controller.as_ref()
                .map(|c| evaluate_scalar(c, time)).unwrap_or(1.0);
            ([x, y, z], [0.0, 0.0, 0.0, 1.0])
        }
        Controller::TM(_) => ([1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]),
    }
}

fn evaluate_scalar(ctrl: &Controller, time: f32) -> f32 {
    match ctrl {
        Controller::Leaf(leaf) => evaluate_leaf_scalar(leaf, time),
        _ => 0.0,
    }
}

// ============================================================================
// Leaf controller evaluation — keyframe interpolation
// ============================================================================

/// Find the surrounding keyframe indices for a given time.
/// Returns (before_index, after_index, interpolation_factor).
fn find_keyframe_pair(keys: &[KeyFrame], time: f32, fps: f32) -> (usize, usize, f32) {
    if keys.is_empty() {
        return (0, 0, 0.0);
    }
    if keys.len() == 1 {
        return (0, 0, 0.0);
    }

    let frame_time = time * fps;

    let mut before = 0;
    let mut after = keys.len() - 1;

    for (i, key) in keys.iter().enumerate() {
        let kf = key.frame() as f32;
        if kf <= frame_time {
            before = i;
        }
        if kf >= frame_time && i > before {
            after = i;
            break;
        }
    }

    if before == after {
        return (before, after, 0.0);
    }

    let before_frame = keys[before].frame() as f32;
    let after_frame = keys[after].frame() as f32;
    let range = after_frame - before_frame;
    let t = if range > 0.0 {
        ((frame_time - before_frame) / range).clamp(0.0, 1.0)
    } else {
        0.0
    };

    (before, after, t)
}

/// Default FPS for keyframe animation (Plasma uses 30 FPS).
const DEFAULT_FPS: f32 = 30.0;

fn evaluate_leaf_scalar(leaf: &LeafController, time: f32) -> f32 {
    if leaf.keys.is_empty() { return 0.0; }
    let (i0, i1, t) = find_keyframe_pair(&leaf.keys, time, DEFAULT_FPS);
    let v0 = key_scalar_value(&leaf.keys[i0]);
    let v1 = key_scalar_value(&leaf.keys[i1]);
    lerp(v0, v1, t)
}

fn evaluate_leaf_point3(leaf: &LeafController, time: f32) -> [f32; 3] {
    if leaf.keys.is_empty() { return [0.0; 3]; }
    let (i0, i1, t) = find_keyframe_pair(&leaf.keys, time, DEFAULT_FPS);
    let v0 = key_point3_value(&leaf.keys[i0]);
    let v1 = key_point3_value(&leaf.keys[i1]);
    lerp3(&v0, &v1, t)
}

fn evaluate_leaf_quat(leaf: &LeafController, time: f32) -> [f32; 4] {
    if leaf.keys.is_empty() { return [0.0, 0.0, 0.0, 1.0]; }
    let (i0, i1, t) = find_keyframe_pair(&leaf.keys, time, DEFAULT_FPS);
    let q0 = key_quat_value(&leaf.keys[i0]);
    let q1 = key_quat_value(&leaf.keys[i1]);
    slerp(&q0, &q1, t)
}

fn evaluate_leaf_scale(leaf: &LeafController, time: f32) -> [f32; 3] {
    evaluate_leaf_scale_with_stretch(leaf, time).0
}

/// Evaluate scale keys returning both scale factors and stretch rotation quaternion.
fn evaluate_leaf_scale_with_stretch(leaf: &LeafController, time: f32) -> ([f32; 3], [f32; 4]) {
    if leaf.keys.is_empty() { return ([1.0; 3], [0.0, 0.0, 0.0, 1.0]); }
    let (i0, i1, t) = find_keyframe_pair(&leaf.keys, time, DEFAULT_FPS);
    let (s0, q0) = key_scale_and_stretch(&leaf.keys[i0]);
    let (s1, q1) = key_scale_and_stretch(&leaf.keys[i1]);
    (lerp3(&s0, &s1, t), slerp(&q0, &q1, t))
}

fn evaluate_leaf_matrix44(leaf: &LeafController, time: f32) -> [f32; 16] {
    if leaf.keys.is_empty() { return identity_matrix(); }
    let (i0, _i1, _t) = find_keyframe_pair(&leaf.keys, time, DEFAULT_FPS);
    key_matrix44_value(&leaf.keys[i0])
}


// ============================================================================
// Key value extraction
// ============================================================================

fn key_scalar_value(key: &KeyFrame) -> f32 {
    match key {
        KeyFrame::Scalar { value, .. } => *value,
        KeyFrame::BezScalar { value, .. } => *value,
        _ => 0.0,
    }
}

fn key_point3_value(key: &KeyFrame) -> [f32; 3] {
    match key {
        KeyFrame::Point3 { value, .. } => *value,
        KeyFrame::BezPoint3 { value, .. } => *value,
        _ => [0.0; 3],
    }
}

fn key_quat_value(key: &KeyFrame) -> [f32; 4] {
    match key {
        KeyFrame::Quat { value, .. } => *value,
        KeyFrame::CompressedQuat32 { data, .. } => decompress_quat32(*data),
        KeyFrame::CompressedQuat64 { data, .. } => decompress_quat64(*data),
        _ => [0.0, 0.0, 0.0, 1.0],
    }
}

fn key_scale_value(key: &KeyFrame) -> [f32; 3] {
    match key {
        KeyFrame::Scale { scale, .. } => *scale,
        KeyFrame::BezScale { scale, .. } => *scale,
        _ => [1.0; 3],
    }
}

fn key_scale_and_stretch(key: &KeyFrame) -> ([f32; 3], [f32; 4]) {
    match key {
        KeyFrame::Scale { scale, quat, .. } => (*scale, *quat),
        KeyFrame::BezScale { scale, quat, .. } => (*scale, *quat),
        _ => ([1.0; 3], [0.0, 0.0, 0.0, 1.0]),
    }
}

fn key_matrix44_value(key: &KeyFrame) -> [f32; 16] {
    match key {
        KeyFrame::Matrix44 { value, .. } => *value,
        _ => identity_matrix(),
    }
}

// ============================================================================
// Math helpers
// ============================================================================

fn identity_matrix() -> [f32; 16] {
    [
        1.0, 0.0, 0.0, 0.0,
        0.0, 1.0, 0.0, 0.0,
        0.0, 0.0, 1.0, 0.0,
        0.0, 0.0, 0.0, 1.0,
    ]
}

fn lerp(a: f32, b: f32, t: f32) -> f32 {
    a + (b - a) * t
}

fn lerp3(a: &[f32; 3], b: &[f32; 3], t: f32) -> [f32; 3] {
    [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)]
}

/// Spherical linear interpolation for quaternions.
/// C++ ref: hsQuat::SetFromSlerp (hsFastMath.cpp)
fn slerp(q0: &[f32; 4], q1: &[f32; 4], t: f32) -> [f32; 4] {
    let mut dot = q0[0]*q1[0] + q0[1]*q1[1] + q0[2]*q1[2] + q0[3]*q1[3];

    let mut q1_adj = *q1;
    if dot < 0.0 {
        dot = -dot;
        q1_adj = [-q1[0], -q1[1], -q1[2], -q1[3]];
    }

    if dot > 0.9995 {
        let result = [
            lerp(q0[0], q1_adj[0], t),
            lerp(q0[1], q1_adj[1], t),
            lerp(q0[2], q1_adj[2], t),
            lerp(q0[3], q1_adj[3], t),
        ];
        return normalize_quat(&result);
    }

    let theta = dot.acos();
    let sin_theta = theta.sin();
    let w0 = ((1.0 - t) * theta).sin() / sin_theta;
    let w1 = (t * theta).sin() / sin_theta;

    [
        q0[0] * w0 + q1_adj[0] * w1,
        q0[1] * w0 + q1_adj[1] * w1,
        q0[2] * w0 + q1_adj[2] * w1,
        q0[3] * w0 + q1_adj[3] * w1,
    ]
}

fn normalize_quat(q: &[f32; 4]) -> [f32; 4] {
    let len = (q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3]).sqrt();
    if len > 1e-10 {
        [q[0]/len, q[1]/len, q[2]/len, q[3]/len]
    } else {
        [0.0, 0.0, 0.0, 1.0]
    }
}

fn euler_to_quat(x: f32, y: f32, z: f32) -> [f32; 4] {
    let (sx, cx) = (x * 0.5).sin_cos();
    let (sy, cy) = (y * 0.5).sin_cos();
    let (sz, cz) = (z * 0.5).sin_cos();

    [
        sx * cy * cz - cx * sy * sz,
        cx * sy * cz + sx * cy * sz,
        cx * cy * sz - sx * sy * cz,
        cx * cy * cz + sx * sy * sz,
    ]
}

/// Convert quaternion to 3x3 rotation matrix embedded in a row-major 4x4.
/// C++ ref: hsQuat::MakeMatrix (hsFastMath.cpp)
fn quat_to_matrix(q: &[f32; 4]) -> [f32; 16] {
    let (x, y, z, w) = (q[0], q[1], q[2], q[3]);
    let xx = x * x; let yy = y * y; let zz = z * z;
    let xy = x * y; let xz = x * z; let yz = y * z;
    let wx = w * x; let wy = w * y; let wz = w * z;

    [
        1.0 - 2.0*(yy+zz), 2.0*(xy-wz),       2.0*(xz+wy),       0.0,
        2.0*(xy+wz),        1.0 - 2.0*(xx+zz), 2.0*(yz-wx),       0.0,
        2.0*(xz-wy),        2.0*(yz+wx),        1.0 - 2.0*(xx+yy), 0.0,
        0.0,                0.0,                0.0,                1.0,
    ]
}

/// Compose Translation × Rotation × Scale into a row-major 4x4 matrix.
/// hsMatrix44 is row-major: fMap[row][col], flat index = row*4+col.
/// Translation at m[3], m[7], m[11].
///
/// C++ ref: hsAffineParts::ComposeMatrix (plTransform.cpp)
fn compose_trs(pos: &[f32; 3], quat: &[f32; 4], scale: &[f32; 3]) -> [f32; 16] {
    let rot = quat_to_matrix(quat);

    [
        rot[0] * scale[0],  rot[1] * scale[1],  rot[2] * scale[2],  pos[0],
        rot[4] * scale[0],  rot[5] * scale[1],  rot[6] * scale[2],  pos[1],
        rot[8] * scale[0],  rot[9] * scale[1],  rot[10] * scale[2], pos[2],
        0.0,                0.0,                0.0,                 1.0,
    ]
}

/// Blend two bone transform matrices by weight.
/// result = (1-weight) * a + weight * b
pub fn blend_matrices(a: &[f32; 16], b: &[f32; 16], weight: f32) -> [f32; 16] {
    let mut result = [0.0f32; 16];
    for i in 0..16 {
        result[i] = a[i] * (1.0 - weight) + b[i] * weight;
    }
    result
}