rusty_skelform 0.4.4

Generic SkelForm runtime for Rust
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
use std::{collections::HashMap, time::Instant};

#[repr(C)]
#[derive(serde::Deserialize, Clone, Debug)]
pub struct Vertex {
    pub pos: Vec2,
    pub uv: Vec2,
    pub init_pos: Vec2,
}

#[derive(serde::Deserialize, Clone, Debug, Default, Copy)]
pub struct Tint {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

#[derive(serde::Deserialize, Clone, Debug, Default, Copy)]
pub struct Vec2 {
    pub x: f32,
    pub y: f32,
}

impl Vec2 {
    pub const fn new(x: f32, y: f32) -> Vec2 {
        Vec2 { x, y }
    }
}

macro_rules! impl_assign_for_vec2 {
    ($trait:ident, $method:ident, $op:tt) => {
        impl std::ops::$trait for Vec2 {
            fn $method(&mut self, other: Vec2) {
                self.x $op other.x;
                self.y $op other.y;
            }
        }
    };
}

macro_rules! impl_assign_f32_for_vec2 {
    ($trait:ident, $method:ident, $op:tt) => {
        impl std::ops::$trait<f32> for Vec2 {
            fn $method(&mut self, other: f32) {
                self.x $op other;
                self.y $op other;
            }
        }
    };
}

macro_rules! impl_for_vec2 {
    ($trait:ident, $method:ident, $op:tt) => {
        impl std::ops::$trait for Vec2 {
            type Output = Self;

            #[inline(always)]
            fn $method(self, rhs: Self) -> Self {
                Self {
                    x: self.x $op rhs.x,
                    y: self.y $op rhs.y,
                }
            }
        }
    };
}

macro_rules! impl_f32_for_vec2 {
    ($trait:ident, $method:ident, $op:tt) => {
        impl std::ops::$trait<f32> for Vec2 {
            type Output = Self;

            #[inline(always)]
            fn $method(self, rhs: f32) -> Self {
                Self {
                    x: self.x $op rhs,
                    y: self.y $op rhs,
                }
            }
        }
    };
}

impl_assign_for_vec2!(AddAssign, add_assign, +=);
impl_assign_for_vec2!(SubAssign, sub_assign, -=);
impl_assign_for_vec2!(DivAssign, div_assign, /=);
impl_assign_for_vec2!(MulAssign, mul_assign, *=);

impl_assign_f32_for_vec2!(AddAssign, add_assign, +=);
impl_assign_f32_for_vec2!(SubAssign, sub_assign, -=);
impl_assign_f32_for_vec2!(DivAssign, div_assign, /=);
impl_assign_f32_for_vec2!(MulAssign, mul_assign, *=);

impl_for_vec2!(Add, add, +);
impl_for_vec2!(Sub, sub, -);
impl_for_vec2!(Mul, mul, *);
impl_for_vec2!(Div, div, /);

impl_f32_for_vec2!(Add, add, +);
impl_f32_for_vec2!(Sub, sub, -);
impl_f32_for_vec2!(Mul, mul, *);
impl_f32_for_vec2!(Div, div, /);

impl PartialEq for Vec2 {
    fn eq(&self, other: &Vec2) -> bool {
        return self.x == other.x && self.y == other.y;
    }
}
#[derive(serde::Deserialize, Clone, Default, Debug)]
#[serde(default)]
pub struct Animation {
    pub name: String,
    pub fps: u32,
    pub keyframes: Vec<Keyframe>,
}
#[derive(serde::Deserialize, Clone, Debug, Default)]
#[serde(default)]
pub struct Bone {
    pub id: u32,
    pub name: String,
    pub parent_id: i32,
    pub tex: String,
    pub tint: Tint,
    pub hidden: bool,

    pub ik_family_id: i32,
    pub ik_constraint: String,
    pub ik_mode: String,
    pub ik_target_id: i32,
    pub ik_bone_ids: Vec<u32>,

    pub vertices: Vec<Vertex>,
    pub indices: Vec<u32>,
    pub binds: Vec<BoneBind>,

    pub phys_global_pos: Vec2,
    pub phys_pos_elasticity: f32,
    pub phys_global_rot: f32,
    pub phys_rot_resistance: f32,
    pub phys_global_scale: Vec2,
    pub phys_scale_elasticity: f32,

    pub rot: f32,
    pub scale: Vec2,
    pub pos: Vec2,
    pub zindex: i32,

    pub init_rot: f32,
    pub init_scale: Vec2,
    pub init_pos: Vec2,
    pub init_tex: String,
    pub init_zindex: i32,
    pub init_tint: Tint,
    pub init_ik_constraint: String,
    pub init_ik_mode: String,
    pub init_hidden: bool,
}

#[derive(serde::Deserialize, Clone, PartialEq, Default, Debug)]
#[serde(default)]
pub struct BoneBind {
    pub bone_id: i32,
    pub is_path: bool,
    pub verts: Vec<BoneBindVert>,
}

#[derive(serde::Deserialize, Clone, PartialEq, Default, Debug)]
#[serde(default)]
pub struct BoneBindVert {
    pub id: u32,
    pub weight: f32,
}

#[derive(Eq, Ord, PartialEq, PartialOrd, serde::Deserialize, Clone, Default, Debug)]
pub enum AnimElement {
    #[default]
    PositionX,
    PositionY,
    Rotation,
    ScaleX,
    ScaleY,
    Zindex,
    Texture,
    IkConstraint,
}

#[derive(PartialEq, serde::Deserialize, Clone, Default, Debug)]
#[serde(default)]
pub struct Keyframe {
    pub frame: u32,
    pub bone_id: u32,
    pub element: String,
    pub value: f32,
    pub value_str: String,
    pub start_handle: Vec2,
    pub end_handle: Vec2,
    pub handle_preset: HandlePreset,
    #[serde(skip)]
    pub label_top: f32,
}

#[derive(PartialEq, serde::Deserialize, Clone, Default, Debug)]
pub enum HandlePreset {
    #[default]
    Linear,
    SineIn,
    SineOut,
    SineInOut,
    None,
    Custom,
}

#[derive(serde::Deserialize, Clone, Default, Debug)]
#[serde(default)]
pub struct Style {
    pub id: u32,
    pub name: String,
    pub active: bool,
    pub textures: Vec<Texture>,
}

#[derive(serde::Deserialize, Clone, Copy, Default, PartialEq, Debug)]
pub enum JointConstraint {
    #[default]
    None,
    Clockwise,
    CounterClockwise,
}

#[derive(serde::Deserialize, Copy, Clone, Default, PartialEq, Debug)]
pub enum InverseKinematicsMode {
    #[default]
    FABRIK,
    Arc,
}

#[derive(serde::Deserialize, Clone, Debug, Default)]
#[serde(default)]
pub struct TexAtlas {
    pub filename: String,
    pub size: Vec2,
}

#[derive(serde::Deserialize, Clone, Debug, Default)]
#[serde(default)]
pub struct Armature {
    pub ik_root_ids: Vec<u32>,
    pub baked_ik: bool,
    pub bones: Vec<Bone>,
    pub cached_bones: Vec<Bone>,
    pub animations: Vec<Animation>,
    pub textures: Vec<Texture>,
    pub styles: Vec<Style>,
    pub atlases: Vec<TexAtlas>,
}

#[derive(serde::Deserialize, Clone, Default, Debug, PartialEq)]
#[serde(default)]
pub struct Texture {
    pub offset: Vec2,
    pub size: Vec2,
    pub name: String,
    pub atlas_idx: u32,
}

/// Process bones with animations.
pub fn animate(
    bones: &mut Vec<Bone>,
    anims: &Vec<&Animation>,
    frames: &Vec<u32>,
    blend_frames: &Vec<u32>,
) {
    for a in 0..anims.len() {
        for b in 0..bones.len() {
            let keyframes = &anims[a].keyframes;
            let b_id = bones[b].id;
            interpolate_bone(&mut bones[b], keyframes, b_id, frames[a], blend_frames[a]);
        }
    }

    for bone in bones {
        reset_bone(bone, frames[0], blend_frames[0], anims);
    }
}

pub fn interpolate_bone(
    bone: &mut Bone,
    keyframes: &Vec<Keyframe>,
    bone_id: u32,
    frame: u32,
    blend_frame: u32,
) {
    let bf = blend_frame;
    interpolate_keyframes("PositionX", &mut bone.pos.x, keyframes, bone_id, frame, bf);
    interpolate_keyframes("PositionY", &mut bone.pos.y, keyframes, bone_id, frame, bf);
    interpolate_keyframes("Rotation", &mut bone.rot, keyframes, bone_id, frame, bf);
    interpolate_keyframes("ScaleX", &mut bone.scale.x, keyframes, bone_id, frame, bf);
    interpolate_keyframes("ScaleY", &mut bone.scale.y, keyframes, bone_id, frame, bf);
    interpolate_keyframes("TintR", &mut bone.tint.r, keyframes, bone_id, frame, bf);
    interpolate_keyframes("TintG", &mut bone.tint.g, keyframes, bone_id, frame, bf);
    interpolate_keyframes("TintB", &mut bone.tint.b, keyframes, bone_id, frame, bf);
    interpolate_keyframes("TintA", &mut bone.tint.a, keyframes, bone_id, frame, bf);

    macro_rules! prev_frame {
        ($element:expr, $field:expr, $kf_value:ident, $value_type:tt) => {
            let prev_frame = get_prev_frame(keyframes, frame, $element, bone.id);
            if prev_frame != usize::MAX {
                $field = keyframes[prev_frame].$kf_value.clone() as $value_type;
            }
        };
    }
    prev_frame!("Texture", bone.tex, value_str, String);
    prev_frame!("Zindex", bone.zindex, value, i32);
    prev_frame!("IkMode", bone.ik_mode, value_str, String);
    prev_frame!("IkConstraint", bone.ik_constraint, value_str, String);

    let prev_frame = get_prev_frame(keyframes, frame, "Hidden", bone.id);
    if prev_frame != usize::MAX {
        bone.hidden = keyframes[prev_frame].value == 1.;
    }
}

pub fn reset_bone(bone: &mut Bone, frame: u32, blend_frame: u32, anims: &Vec<&Animation>) {
    let z = Vec2::new(0., 0.);
    macro_rules! interp {
        ($element:expr, $field:expr, $init_field:expr) => {
            if !is_animated(bone.id, $element, anims) {
                $field = interpolate(frame, blend_frame, $field, $init_field, z, z);
            }
        };
    }
    interp!("PositionX", bone.pos.x, bone.init_pos.x);
    interp!("PositionY", bone.pos.y, bone.init_pos.y);
    interp!("Rotation", bone.rot, bone.init_rot);
    interp!("ScaleX", bone.scale.x, bone.init_scale.x);
    interp!("ScaleY", bone.scale.y, bone.init_scale.y);

    macro_rules! hard_interp {
        ($element:expr, $field:expr, $init_field:expr) => {
            if !is_animated(bone.id, $element, anims) {
                $field = $init_field.clone();
            }
        };
    }
    hard_interp!("Texture", bone.tex, bone.init_tex);
    hard_interp!("Zindex", bone.zindex, bone.init_zindex);
    hard_interp!("Hidden", bone.hidden, bone.init_hidden);
    hard_interp!("IkMode", bone.ik_mode, bone.init_ik_mode);
    hard_interp!("IkConstraint", bone.ik_constraint, bone.init_ik_constraint);
}

pub fn get_bone_texture(bone_tex: String, styles: &Vec<&Style>) -> Option<Texture> {
    for style in styles {
        if let Some(tex) = style.textures.iter().find(|t| t.name == bone_tex) {
            return Some(tex.clone());
        }
    }
    return None;
}

pub fn is_animated(bone_id: u32, el: &str, anims: &Vec<&Animation>) -> bool {
    for anim in anims {
        for kf in &anim.keyframes {
            if kf.bone_id == bone_id && kf.element == el {
                return true;
            }
        }
    }
    false
}

/// Apply child-parent inheritance.
/// Must be run twice, before and after `inverse_kinematics()`.
pub fn inheritance(bones: &mut Vec<Bone>, ik_rots: HashMap<u32, f32>, armature_bones: &Vec<Bone>) {
    for b in 0..bones.len() {
        if bones[b].parent_id != -1 {
            let parent = &bones[bones[b].parent_id as usize];
            let parent_pos = parent.pos;
            let parent_rot = parent.rot;
            let parent_scale = parent.scale;

            bones[b].rot += parent.rot;
            bones[b].scale *= parent_scale;
            bones[b].pos *= parent_scale;
            bones[b].pos = rotate(&bones[b].pos, parent_rot);
            bones[b].pos += parent_pos;
        }

        if let Some(ik_rot) = ik_rots.get(&(b as u32)) {
            bones[b].rot = *ik_rot;
        }

        // apply physics, if armature_bones is provided
        if armature_bones.len() > 0 {
            if bones[b].phys_rot_resistance > 1. {
                bones[b].rot = armature_bones[b].phys_global_rot;
            }
            if bones[b].phys_pos_elasticity > 0. {
                bones[b].pos = armature_bones[b].phys_global_pos;
            }
            if bones[b].phys_scale_elasticity > 0. {
                bones[b].scale = armature_bones[b].phys_global_scale;
            }
        }
    }
}

/// Always run this before `inheritance()`.`
pub fn reset_inheritance(cached_bones: &mut Vec<Bone>, bones: &Vec<Bone>) {
    for b in 0..bones.len() {
        cached_bones[b].pos = bones[b].pos;
        cached_bones[b].rot = bones[b].rot;
        cached_bones[b].scale = bones[b].scale;
    }
}

pub fn construct(armature: &mut Armature) {
    // initialize cached_bones
    if armature.cached_bones.len() == 0 {
        armature.cached_bones = armature.bones.clone();
    } else {
        armature
            .cached_bones
            .sort_by(|a, b| a.id.partial_cmp(&b.id).unwrap());
    }

    // process IK if this file isn't baked
    let mut ik_rots = HashMap::new();
    if !armature.baked_ik && armature.ik_root_ids.len() > 0 {
        reset_inheritance(&mut armature.cached_bones, &armature.bones);
        inheritance(&mut armature.cached_bones, HashMap::new(), &vec![]);
        ik_rots = inverse_kinematics(&mut armature.cached_bones, armature.ik_root_ids.clone());
    }
    reset_inheritance(&mut armature.cached_bones, &armature.bones);
    inheritance(&mut armature.cached_bones, ik_rots.clone(), &vec![]);

    // // simulate physics
    // simulate_physics(&mut armature.bones, &mut armature.cached_bones);
    // reset_inheritance(&mut armature.cached_bones, &armature.bones);
    // inheritance(&mut armature.cached_bones, ik_rots, &armature.bones);

    // mesh deformation
    construct_verts(&mut armature.cached_bones);
}

#[allow(unused)]
fn simulate_physics(armature_bones: &mut Vec<Bone>, constructed_bones: &mut Vec<Bone>) {
    // interpolate global fields, based on constructed bones
    for b in 0..armature_bones.len() {
        let s = Vec2::new(0.3, 0.3);
        let e = Vec2::new(0.6, 0.6);
        let arm_bone = &mut armature_bones[b];
        let const_bone = &constructed_bones[b];
        let prev_pos = arm_bone.phys_global_pos;

        // interpolate position
        if arm_bone.phys_pos_elasticity > 0. || arm_bone.phys_rot_resistance > 0. {
            let phys_pos = &mut arm_bone.phys_global_pos;
            let elasticity = arm_bone.phys_pos_elasticity;
            phys_pos.x = interpolate(2, elasticity as u32, phys_pos.x, const_bone.pos.x, s, e);
            phys_pos.y = interpolate(2, elasticity as u32, phys_pos.y, const_bone.pos.y, s, e);
        }

        // interpolate rotation
        // 'interpolation' here is conceptual - to avoid roundabouts, shortest_delta is always used
        if arm_bone.phys_rot_resistance > 0. {
            // swing rotation based on momentum
            let vel = normalize(arm_bone.phys_global_pos - prev_pos);
            let angle = (-vel.y).atan2(-vel.x);
            let rot = shortest_angle_delta(arm_bone.phys_global_rot, angle);
            if arm_bone.phys_rot_resistance > 50. {
                let strength = magnitude(arm_bone.phys_global_pos - prev_pos);
                arm_bone.phys_global_rot += rot * strength / arm_bone.phys_rot_resistance;
            }

            // slowly reset rotation back to rest
            let rot = shortest_angle_delta(arm_bone.phys_global_rot, const_bone.rot);
            arm_bone.phys_global_rot += rot / 10.;
        }

        // interpolate scale
        if arm_bone.phys_scale_elasticity > 0. {
            let phys_scale = &mut arm_bone.phys_global_scale;
            let elas = arm_bone.phys_scale_elasticity;
            phys_scale.x = interpolate(2, elas as u32, phys_scale.x, const_bone.scale.x, s, e);
            phys_scale.y = interpolate(2, elas as u32, phys_scale.y, const_bone.scale.y, s, e);
        }
    }
}

pub fn construct_verts(bones: &mut Vec<Bone>) {
    for b in 0..bones.len() {
        // move vertex to main bone.
        // this will be overridden if vertex has a bind.
        for v in 0..bones[b].vertices.len() {
            bones[b].vertices[v].pos = bones[b].vertices[v].init_pos;
            bones[b].vertices[v].pos = inherit_vert(bones[b].vertices[v].pos, &bones[b]);
        }

        for bi in 0..bones[b].binds.len() {
            let b_id = bones[b].binds[bi].bone_id;
            if b_id == -1 {
                continue;
            }
            let bind_bone = bones
                .iter()
                .find(|bone| bone.id == b_id as u32)
                .unwrap()
                .clone();
            for v in 0..bones[b].binds[bi].verts.len() {
                let vert_id = bones[b].binds[bi].verts[v].id as usize;

                if !bones[b].binds[bi].is_path {
                    // weights
                    let weight = bones[b].binds[bi].verts[v].weight;
                    let end_pos = inherit_vert(bones[b].vertices[vert_id].init_pos, &bind_bone)
                        - bones[b].vertices[vert_id].pos;
                    bones[b].vertices[vert_id].pos += end_pos * weight;
                    continue;
                }

                // pathing:
                // Bone binds are treated as one continuous line.
                // Vertices will follow along this path.

                // get previous and next bone
                let binds = &bones[b].binds;
                let prev = if bi > 0 { bi - 1 } else { bi };
                let next = (bi + 1).min(binds.len() - 1);
                let prev_bone = bones
                    .iter()
                    .find(|bone| bone.id == binds[prev].bone_id as u32);
                let next_bone = bones
                    .iter()
                    .find(|bone| bone.id == binds[next].bone_id as u32);

                // get the average of normals between previous bone, this bone, and next bone
                let prev_dir = bind_bone.pos - prev_bone.unwrap().pos;
                let next_dir = next_bone.unwrap().pos - bind_bone.pos;
                let prev_normal = normalize(Vec2::new(-prev_dir.y, prev_dir.x));
                let next_normal = normalize(Vec2::new(-next_dir.y, next_dir.x));
                let average = prev_normal + next_normal;
                let normal_angle = average.y.atan2(average.x);

                // move vertex to bind bone, then just adjust it to 'bounce' off the line's surface
                bones[b].vertices[vert_id].pos =
                    bones[b].vertices[vert_id].init_pos + bind_bone.pos;
                let rotated = rotate(
                    &(bones[b].vertices[vert_id].pos - bind_bone.pos),
                    normal_angle,
                );
                bones[b].vertices[vert_id].pos =
                    bind_bone.pos + (rotated * bones[b].binds[bi].verts[v].weight);
            }
        }
    }
}

pub fn inherit_vert(mut pos: Vec2, bone: &Bone) -> Vec2 {
    pos *= bone.scale;
    pos = rotate(&pos, bone.rot);
    pos += bone.pos;
    pos
}

fn magnitude(vec: Vec2) -> f32 {
    (vec.x * vec.x + vec.y * vec.y).sqrt()
}

fn normalize(vec: Vec2) -> Vec2 {
    let mag = magnitude(vec);
    if mag == 0. {
        return Vec2::default();
    }
    Vec2::new(vec.x / mag, vec.y / mag)
}

fn rotate(point: &Vec2, rot: f32) -> Vec2 {
    Vec2 {
        x: point.x * rot.cos() - point.y * rot.sin(),
        y: point.x * rot.sin() + point.y * rot.cos(),
    }
}

fn get_prev_frame(keyframes: &Vec<Keyframe>, frame: u32, element: &str, id: u32) -> usize {
    let mut prev = usize::MAX;
    for (i, kf) in keyframes.iter().enumerate() {
        if kf.frame <= frame && kf.element == element && kf.bone_id == id {
            prev = i;
        }
    }
    prev
}

fn get_next_frame(keyframes: &Vec<Keyframe>, frame: u32, element: &str, id: u32) -> usize {
    for (i, kf) in keyframes.iter().enumerate() {
        if kf.frame > frame && kf.element == element && kf.bone_id == id {
            return i;
        }
    }
    usize::MAX
}

/// Interpolate an f32 value from the specified keyframe data.
pub fn interpolate_keyframes(
    element: &str,
    field: &mut f32,
    keyframes: &Vec<Keyframe>,
    id: u32,
    frame: u32,
    blend_frames: u32,
) {
    let mut prev = get_prev_frame(keyframes, frame, element, id);
    let mut next = get_next_frame(keyframes, frame, element, id);

    // ensure both frames are pointing somewhere
    if prev == usize::MAX {
        prev = next;
    } else if next == usize::MAX {
        next = prev;
    }

    // if both are max, then the frame doesn't exist. Fallbackt to init value
    if prev == usize::MAX && next == usize::MAX {
        return;
    }

    let total_frames = keyframes[next].frame - keyframes[prev].frame;
    let current_frame = frame - keyframes[prev].frame;

    let result = interpolate(
        current_frame,
        total_frames,
        keyframes[prev].value,
        keyframes[next].value,
        keyframes[next].start_handle,
        keyframes[next].end_handle,
    );

    let z = Vec2::new(0., 0.);
    *field = interpolate(current_frame, blend_frames, *field, result, z, z);
}

fn interpolate(
    current: u32,
    max: u32,
    start_val: f32,
    end_val: f32,
    start_handle: Vec2,
    end_handle: Vec2,
) -> f32 {
    // snapping behavior for None transition preset
    if start_handle.y == 999. && end_handle.y == 999. {
        return start_val;
    }
    if max == 0 || current >= max {
        return end_val;
    }

    // solve for time (x axis) with Newton-Raphson
    let initial = current as f32 / max as f32;
    let mut t = initial;
    for _ in 0..5 {
        let x = cubic_bezier(t, start_handle.x, end_handle.x);
        let dx = cubic_bezier_derivative(t, start_handle.x, end_handle.x);
        if dx.abs() < 1e-5 {
            break;
        }
        t -= (x - initial) / dx;
        t = t.clamp(0., 1.);
    }

    let progress = cubic_bezier(t, start_handle.y, end_handle.y);
    start_val + (end_val - start_val) * progress
}

fn cubic_bezier(t: f32, p1: f32, p2: f32) -> f32 {
    let u = 1. - t;
    3. * u * u * t * p1 + 3. * u * t * t * p2 + t * t * t
}

fn cubic_bezier_derivative(t: f32, p1: f32, p2: f32) -> f32 {
    let u = 1. - t;
    return 3. * u * u * p1 + 6. * u * t * (p2 - p1) + 3. * t * t * (1. - p2);
}

/// Get rotations based on inverse kinematics.
/// Must be run between two `inheritance()`, with 2nd call using rotations from this.
pub fn inverse_kinematics(bones: &mut Vec<Bone>, ik_root_ids: Vec<u32>) -> HashMap<u32, f32> {
    let mut ik_rot: HashMap<u32, f32> = HashMap::new();

    for root_id in ik_root_ids {
        let family = bones[root_id as usize].clone();
        if family.ik_target_id == -1 {
            continue;
        }
        let root = bones[family.ik_bone_ids[0] as usize].pos;
        let target = bones[family.ik_target_id as usize].pos;
        let mut family_bones: Vec<&mut Bone> = bones
            .iter_mut()
            .filter(|bone| family.ik_bone_ids.contains(&bone.id))
            .collect();

        if family.ik_mode == "FABRIK" {
            for _ in 0..10 {
                fabrik(&mut family_bones, root, target);
            }
        } else {
            arc_ik(&mut family_bones, root, target)
        }
        point_bones(bones, family.clone());
        apply_constraints(bones, family.clone());
        for b in 0..family.ik_bone_ids.len() {
            if b == family.ik_bone_ids.len() - 1 {
                continue;
            }
            ik_rot.insert(
                family.ik_bone_ids[b],
                bones[family.ik_bone_ids[b] as usize].rot,
            );
        }
    }

    ik_rot
}

pub fn point_bones(bones: &mut Vec<Bone>, family: Bone) {
    let end_bone = &bones[*family.ik_bone_ids.last().unwrap() as usize];
    let mut tip_pos = end_bone.pos;
    for i in (0..family.ik_bone_ids.len()).rev() {
        if i == family.ik_bone_ids.len() - 1 {
            continue;
        }
        let bone = &mut bones[family.ik_bone_ids[i] as usize];

        let dir = tip_pos - bone.pos;
        bone.rot = dir.y.atan2(dir.x);
        tip_pos = bone.pos;
    }
}

pub fn apply_constraints(bones: &mut Vec<Bone>, family: Bone) {
    let root = bones[family.ik_bone_ids[0] as usize].pos;
    let target = bones[family.ik_target_id as usize].pos;
    let joint_dir = normalize(bones[family.ik_bone_ids[1] as usize].pos - root);
    let base_dir = normalize(target - root);
    let dir = joint_dir.x * base_dir.y - base_dir.x * joint_dir.y;
    let base_angle = base_dir.y.atan2(base_dir.x);

    let cw = family.ik_constraint == "Clockwise" && dir > 0.;
    let ccw = family.ik_constraint == "CounterClockwise" && dir < 0.;
    if ccw || cw {
        for i in &family.ik_bone_ids {
            bones[*i as usize].rot = -bones[*i as usize].rot + base_angle * 2.;
        }
    }
}

// https://www.youtube.com/watch?v=NfuO66wsuRg
pub fn fabrik(bones: &mut Vec<&mut Bone>, root: Vec2, target: Vec2) {
    // forward-reaching
    let mut next_pos: Vec2 = target;
    let mut next_length = 0.;
    for b in (0..bones.len()).rev() {
        let length = normalize(next_pos - bones[b].pos) * next_length;
        if b != 0 {
            next_length = magnitude(bones[b].pos - bones[b - 1].pos);
        }
        bones[b].pos = next_pos - length;
        next_pos = bones[b].pos;
    }

    // backward-reaching
    let mut prev_pos: Vec2 = root;
    let mut prev_length = 0.;
    for b in 0..bones.len() {
        let length = normalize(prev_pos - bones[b].pos) * prev_length;
        if b != bones.len() - 1 {
            prev_length = magnitude(bones[b].pos - bones[b + 1].pos);
        }
        bones[b].pos = prev_pos - length;
        prev_pos = bones[b].pos;
    }
}

pub fn arc_ik(bones: &mut Vec<&mut Bone>, root: Vec2, target: Vec2) {
    // determine where bones will be on the arc line (ranging from 0 to 1)
    let mut dist: Vec<f32> = vec![0.];

    let max_length = magnitude(bones.last().unwrap().pos - root);
    let mut curr_length = 0.;
    for b in 1..bones.len() {
        let length = magnitude(bones[b].pos - bones[b - 1].pos);
        curr_length += length;
        dist.push(curr_length / max_length);
    }

    let base = target - root;
    let base_angle = base.y.atan2(base.x);
    let base_mag = magnitude(base).min(max_length);
    let peak = max_length / base_mag;
    let valley = base_mag / max_length;

    for b in 1..bones.len() {
        bones[b].pos = Vec2::new(
            bones[b].pos.x * valley,
            root.y + (1. - peak) * (dist[b] * 3.14).sin() * base_mag,
        );

        let rotated = rotate(&(bones[b].pos - root), base_angle);
        bones[b].pos = rotated + root;
    }
}

pub fn format_frame(mut frame: u32, animation: &Animation, reverse: bool, is_loop: bool) -> u32 {
    let last_frame = animation.keyframes.last().unwrap().frame;

    if is_loop {
        frame %= last_frame + 1
    }

    if reverse {
        frame = last_frame - frame
    }

    frame
}

pub fn time_frame(time: Instant, animation: &Animation, reverse: bool, is_loop: bool) -> u32 {
    let elapsed = time.elapsed().as_millis() as f32 / 1e3 as f32;
    let frametime = 1. / animation.fps as f32;

    let mut frame = (elapsed / frametime) as u32;
    frame = format_frame(frame, animation, reverse, is_loop);

    frame
}

/// Flips the bone if either if its scale is negative.
pub fn check_flip(bone: &mut Bone, scale: Vec2) {
    let both = scale.x < 0. && scale.y < 0.;
    let either = scale.x < 0. || scale.y < 0.;
    if either && !both {
        bone.rot = -bone.rot;
    }
}

pub fn shortest_angle_delta(from: f32, to: f32) -> f32 {
    let pi = 3.141592653589793;
    let tau = pi * 2.0;
    let mut delta = to - from;
    while delta > pi {
        delta -= tau;
    }
    while delta < -pi {
        delta += tau;
    }
    delta
}