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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
use na::{Isometry3, Point3, RealField, Scalar, Translation3, UnitQuaternion, Vector3};

/// One's skeleton.
/// Parameterized with numric value and bone userdata type.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde-1", derive(serde::Serialize, serde::Deserialize))]
pub struct Skelly<T: Scalar, D = ()> {
    bones: Vec<Bone<T, D>>,
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde-1", derive(serde::Serialize, serde::Deserialize))]
struct Bone<T: Scalar, D> {
    isometry: Isometry3<T>,
    parent: Option<usize>,
    userdata: D,
}

impl<T, D> Skelly<T, D>
where
    T: Scalar,
{
    /// Returns new empty skelly.
    ///
    /// # Example
    ///
    /// ```
    /// # use skelly::Skelly;
    /// let skelly = Skelly::<f32>::new();
    /// ```
    pub fn new() -> Self {
        Skelly { bones: Vec::new() }
    }

    /// Creates new root bone in the skelly at specified `position`.
    ///
    /// Root bones are ones that have no parent bone.\
    /// Returns id of the added root bone.\
    /// `userdata` will be associated with the bone.
    /// It maybe be accessed with
    /// [`Skelly::get_userdata`] and [`Skelly::get_userdata_mut`]
    /// using returned id.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::Point3};
    /// let mut skelly = Skelly::<f32, &str>::new();
    /// let root = skelly.add_root_with(Point3::origin(), "root-user-data");
    /// ```
    pub fn add_root_with(&mut self, position: Point3<T>, userdata: D) -> usize
    where
        T: RealField,
    {
        self.bones.push(Bone {
            isometry: Isometry3 {
                rotation: UnitQuaternion::identity(),
                translation: position.coords.into(),
            },
            parent: None,
            userdata,
        });
        self.bones.len() - 1
    }

    /// Attaches new bone to an existing bone with specified id.
    ///
    /// Returns id of the added bone.\
    /// The bone will be placed `relative` to its parent.\
    /// `userdata` will be associated with the bone.
    /// It maybe be accessed with
    /// [`Skelly::get_userdata`] and [`Skelly::get_userdata_mut`]
    /// using returned id.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Vector3}};
    /// let mut skelly = Skelly::<f32, &str>::new();
    /// let root = skelly.add_root_with(Point3::origin(), "root-user-data");
    /// let bone = skelly.attach_with(Vector3::x(), root, "bone-user-data");
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `parent` index is out of bounds.
    #[track_caller]
    pub fn attach_with(&mut self, relative: Vector3<T>, parent: usize, userdata: D) -> usize
    where
        T: RealField,
    {
        assert!(parent < self.bones.len(), "Parent index is ouf of bounds");
        self.bones.push(Bone {
            isometry: Isometry3 {
                rotation: UnitQuaternion::identity(),
                translation: relative.into(),
            },
            parent: Some(parent),
            userdata,
        });

        self.bones.len() - 1
    }

    /// Rotates bone with specified id.
    ///
    /// *Does not* affect relative position to the parent and global position for root bones.
    /// Affects global position of all descendant bones.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Isometry3, UnitQuaternion, Vector3}, core::f32::{consts::PI, EPSILON}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut globals = [Isometry3::identity(); 2];
    /// skelly.write_globals(&Isometry3::identity(), &mut globals);
    /// let bone_global_old = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at (1, 0, 0).
    /// assert!((bone_global_old.translation.vector - Vector3::x()).magnitude() < EPSILON);
    ///
    /// // Rotate root bone. It is still at origin.
    /// // Yet global position of the `bone` attached to `root` has changed accordingly.
    /// skelly.append_rotation(root, UnitQuaternion::from_euler_angles(0.0, 0.0, PI / 2.0));
    ///
    /// skelly.write_globals(&Isometry3::identity(), &mut globals);
    /// let bone_global_new = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space after root rotation at (0, 1, 0).
    /// assert!((bone_global_new.translation.vector - Vector3::y()).magnitude() < EPSILON);
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    #[track_caller]
    pub fn append_rotation(&mut self, bone: usize, rotation: UnitQuaternion<T>)
    where
        T: RealField,
    {
        self.bones[bone].isometry.rotation *= rotation
    }

    /// Rotates bone with specified id.
    ///
    /// Affect relative position to the parent and global position for root bones.
    /// Affects global position of all descendant bones.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Isometry3, UnitQuaternion, Vector3}, core::f32::{consts::PI, EPSILON}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut globals = [Isometry3::identity(); 2];
    /// skelly.write_globals(&Isometry3::identity(), &mut globals);
    /// let bone_global_old = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at (1, 0, 0).
    /// assert!((bone_global_old.translation.vector - Vector3::x()).magnitude() < EPSILON);
    ///
    /// // Rotate the bone. It is still at origin.
    /// // Yet global position of the `bone` attached to `root` has changed accordingly.
    /// skelly.prepend_rotation(bone, UnitQuaternion::from_euler_angles(0.0, 0.0, PI / 2.0));
    ///
    /// skelly.write_globals(&Isometry3::identity(), &mut globals);
    /// let bone_global_new = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space after root rotation at (0, 1, 0).
    /// assert!((bone_global_new.translation.vector - Vector3::y()).magnitude() < EPSILON);
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    #[track_caller]
    pub fn prepend_rotation(&mut self, bone: usize, rotation: UnitQuaternion<T>)
    where
        T: RealField,
    {
        let my_isometry = &mut self.bones[bone].isometry;
        *my_isometry = rotation * *my_isometry;
    }

    /// Translates bone with specified id.
    ///
    /// Affects relative position to the parent and global position for root bones.
    /// Affects global position of all descendant bones.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Isometry3, UnitQuaternion, Vector3}, core::f32::{consts::PI, EPSILON}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut globals = [Isometry3::identity(); 2];
    /// skelly.write_globals(&Isometry3::identity(), &mut globals);
    /// let bone_global_old = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at (1, 0, 0).
    /// assert!((bone_global_old.translation.vector - Vector3::x()).magnitude() < EPSILON);
    ///
    /// // Translate root bone.
    /// // Global position of the `bone` attached to `root` has changed accordingly.
    /// skelly.append_translation(root, Vector3::z().into());
    ///
    /// skelly.write_globals(&Isometry3::identity(), &mut globals);
    /// let bone_global_new = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space after root translation at (1, 0, 1).
    /// assert!((bone_global_new.translation.vector - (Vector3::x() + Vector3::z())).magnitude() < EPSILON);
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    #[track_caller]
    pub fn append_translation(&mut self, bone: usize, translation: Translation3<T>)
    where
        T: RealField,
    {
        self.bones[bone].isometry.translation *= translation;
    }

    /// Sets relative position for bone with specified id.
    /// Affects global position of all descendant bones.
    ///
    /// This method ignores current relative position of the bone.
    /// To apply translation to current relative poistion see [`Skelly::append_translation`].
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Isometry3, UnitQuaternion, Vector3}, core::f32::{consts::PI, EPSILON}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut globals = [Isometry3::identity(); 2];
    /// skelly.write_globals(&Isometry3::identity(), &mut globals);
    /// let bone_global_old = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at (1, 0, 0).
    /// assert!((bone_global_old.translation.vector - Vector3::x()).magnitude() < EPSILON);
    ///
    /// // Set new relative position for the `bone`.
    /// skelly.set_position(bone, Vector3::z());
    ///
    /// skelly.write_globals(&Isometry3::identity(), &mut globals);
    /// let bone_global_new = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at new position (0, 0, 1).
    /// assert!((bone_global_new.translation.vector - Vector3::z()).magnitude() < EPSILON);
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    #[track_caller]
    pub fn set_position(&mut self, bone: usize, position: Vector3<T>) {
        self.bones[bone].isometry.translation = position.into();
    }

    /// Returns current bone position relative to parent.
    #[track_caller]
    pub fn get_position(&mut self, bone: usize) -> Vector3<T>
    where
        T: RealField,
    {
        self.bones[bone].isometry.translation.vector
    }

    /// Sets relative orientation for bone with specified id.
    /// Affects global position of all descendant bones.
    ///
    /// This method ignores current relative position of the bone.
    /// To apply translation to current relative poistion see [`Skelly::append_translation`].
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Isometry3, UnitQuaternion, Vector3}, core::f32::{consts::PI, EPSILON}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut globals = [Isometry3::identity(); 2];
    /// skelly.write_globals(&Isometry3::identity(), &mut globals);
    /// let bone_global_old = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at (1, 0, 0).
    /// assert!((bone_global_old.translation.vector - Vector3::x()).magnitude() < EPSILON);
    ///
    /// // Set new relative orientation for the `bone`.
    /// skelly.set_orientation(root, UnitQuaternion::from_euler_angles(0.0, 0.0, PI / 2.0));
    ///
    /// skelly.write_globals(&Isometry3::identity(), &mut globals);
    /// let bone_global_new = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at new position (0, 0, 1).
    /// assert!((bone_global_new.translation.vector - Vector3::y()).magnitude() < EPSILON);
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    #[track_caller]
    pub fn set_orientation(&mut self, bone: usize, orientation: UnitQuaternion<T>) {
        self.bones[bone].isometry.rotation = orientation;
    }

    /// Returns current bone orientation relative to parent.
    #[track_caller]
    pub fn get_orientation(&mut self, bone: usize) -> UnitQuaternion<T>
    where
        T: RealField,
    {
        self.bones[bone].isometry.rotation
    }

    /// Returns current bone isometry relative to parent.
    #[track_caller]
    pub fn get_isometry(&mut self, bone: usize) -> Isometry3<T>
    where
        T: RealField,
    {
        self.bones[bone].isometry
    }

    /// Returns reference to userdata associated with the `bone`.
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Vector3}};
    /// let mut skelly = Skelly::<f32, &str>::new();
    /// let root = skelly.add_root_with(Point3::origin(), "root-bone-data");
    /// let bone = skelly.attach_with(Vector3::x(), root, "another-bone-data");
    ///
    /// assert_eq!(*skelly.get_userdata(root), "root-bone-data");
    /// assert_eq!(*skelly.get_userdata(bone), "another-bone-data");
    /// ```
    #[track_caller]
    pub fn get_userdata(&self, bone: usize) -> &D {
        &self.bones[bone].userdata
    }

    /// Returns mutable reference to userdata associated with the `bone`.
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Vector3}};
    /// let mut skelly = Skelly::<f32, Vec<&str>>::new();
    /// let root = skelly.add_root_with(Point3::origin(), vec![]);
    ///
    /// skelly.get_userdata_mut(root).push("another-root-data-entry");
    /// assert_eq!(*skelly.get_userdata(root), ["another-root-data-entry"]);
    /// ```
    #[track_caller]
    pub fn get_userdata_mut(&mut self, bone: usize) -> &mut D {
        &mut self.bones[bone].userdata
    }

    /// Associated new userdata with the `bone`.
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Vector3}};
    /// let mut skelly = Skelly::<f32, &str>::new();
    /// let root = skelly.add_root_with(Point3::origin(), "initial-root-data");
    ///
    /// skelly.set_userdata(root, "new-root-data");
    /// assert_eq!(*skelly.get_userdata(root), "new-root-data");
    /// ```
    #[track_caller]
    pub fn set_userdata(&mut self, bone: usize, userdata: D) {
        self.bones[bone].userdata = userdata
    }

    /// Returns parent of the specified `bone`.
    /// Returns `None` for root bones.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Vector3}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// assert_eq!(skelly.get_parent(bone), Some(root));
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    #[track_caller]
    pub fn get_parent(&self, bone: usize) -> Option<usize> {
        self.bones[bone].parent
    }

    /// Returns number of bones in the skelly.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Vector3}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// assert_eq!(skelly.len(), 2);
    /// ```
    pub fn len(&self) -> usize {
        self.bones.len()
    }

    /// Fills slice of `Isometry3` with global isometries
    /// for each bone of the skelly.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Vector3, Isometry3}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut globals = [Isometry3::identity(); 2];
    /// skelly.write_globals(&Isometry3::identity(), &mut globals);
    /// ```
    pub fn write_globals(&self, skelly_global: &Isometry3<T>, globals: &mut [Isometry3<T>])
    where
        T: RealField,
    {
        self.bones
            .iter()
            .take(globals.len())
            .enumerate()
            .for_each(|(index, bone)| match bone.parent {
                Some(parent) => {
                    debug_assert!(parent < index);
                    globals[index] = globals[parent] * bone.isometry;
                }
                None => {
                    globals[index] = skelly_global * bone.isometry;
                }
            })
    }

    /// Makes the skelly to assume specifed posture.
    #[track_caller]
    pub fn assume_posture(&mut self, posture: &Posture<T>)
    where
        T: Copy,
    {
        assert_eq!(self.bones.len(), posture.joints.len());

        self.bones
            .iter_mut()
            .zip(&posture.joints)
            .for_each(|(bone, isometry)| bone.isometry = *isometry);
    }

    /// Iterates through bone ancestors up until root bone is reached
    /// yielding their ids.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Vector3, Isometry3}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    /// let tip = skelly.attach(Vector3::x(), bone);
    ///
    /// assert_eq!(skelly.iter_chain(tip).collect::<Vec<_>>(), [bone, root]);
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    pub fn iter_chain(&self, mut bone: usize) -> impl Iterator<Item = usize> + '_ {
        std::iter::from_fn(move || {
            if let Some(parent) = self.bones[bone].parent {
                bone = parent;
                Some(bone)
            } else {
                None
            }
        })
    }

    /// Iterates through the bone's direct descendants
    /// yielding their ids.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Vector3, Isometry3}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let left = skelly.attach(Vector3::x(), root);
    /// let right = skelly.attach(Vector3::x(), root);
    ///
    /// assert_eq!(skelly.iter_children(root).collect::<Vec<_>>(), [left, right]);
    /// ```
    ///
    /// This method is not very efficient.
    /// As it effectively scans sub-slice [bone..]
    /// Use with caution for too complex skellies in hot-paths.
    ///
    /// TODO: Consider adding skelly building phase to pack siblings together.
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    #[track_caller]
    pub fn iter_children(&self, parent: usize) -> impl Iterator<Item = usize> + '_ {
        self.bones
            .iter()
            .enumerate()
            .skip(parent)
            .filter_map(move |(index, bone)| {
                if bone.parent == Some(parent) {
                    Some(index)
                } else {
                    None
                }
            })
    }
}

impl<T> Skelly<T>
where
    T: Scalar,
{
    /// Creates new root bone in the skelly at specified `position`.
    ///
    /// Root bones are ones that have no parent bone.\
    /// Returns id of the added root bone.\
    ///
    /// `skelly.add_root(pos)` is a more pleasant shorthand for `skelly.add_root_with(pos, ())`;
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::Point3};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// ```
    pub fn add_root(&mut self, position: Point3<T>) -> usize
    where
        T: RealField,
    {
        self.add_root_with(position, ())
    }

    /// Attaches new bone to an existing bone with specified id.
    ///
    /// Returns id of the added bone.\
    /// The bone will be placed `relative` to its parent.\
    ///
    /// `skelly.attach(relative, parent)` is a more pleasant shorthand for `skelly.attach_with(relative, parent, ())`;
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::Skelly, na::{Point3, Vector3}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `parent` index is out of bounds.
    #[track_caller]
    pub fn attach(&mut self, relative: Vector3<T>, parent: usize) -> usize
    where
        T: RealField,
    {
        self.attach_with(relative, parent, ())
    }
}

/// Collection of bones transformations
/// that represent a skelly posture.
///
/// It's primary usecase is to be used instead
/// of transformations contained in the `Skelly`.
/// Multiple postures to be processed for the same `Skelly`.
/// Allowing running animations, IK algorithms etc,
/// and then blend them to get final posture.
pub struct Posture<T: Scalar> {
    joints: Vec<Isometry3<T>>,
}

impl<T> Posture<T>
where
    T: Scalar,
{
    /// Returns new `Posture` instance for `skelly`.
    /// Copies current `skelly` transformations.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::{Skelly, Posture}, na::{Point3, Vector3}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut posture = Posture::new(&skelly);
    /// ```
    pub fn new<D>(skelly: &Skelly<T, D>) -> Self
    where
        T: RealField,
    {
        Posture {
            joints: skelly.bones.iter().map(|bone| bone.isometry).collect(),
        }
    }

    pub fn is_compatible<D>(&self, skelly: &Skelly<T, D>) -> bool {
        self.joints.len() == skelly.bones.len()
    }

    /// Rotates bone with specified id.
    ///
    /// *Does not* affect relative position to the parent and global position for root bones.
    /// Affects global position of all descendant bones.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::{Skelly, Posture}, na::{Point3, Isometry3, UnitQuaternion, Vector3}, core::f32::{consts::PI, EPSILON}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut posture = Posture::new(&skelly);
    ///
    /// let mut globals = [Isometry3::identity(); 2];
    /// posture.write_globals(&skelly, &Isometry3::identity(), &mut globals);
    /// let bone_global_old = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at (1, 0, 0).
    /// assert!((bone_global_old.translation.vector - Vector3::x()).magnitude() < EPSILON);
    ///
    /// // Rotate root bone. It is still at origin.
    /// // Yet global position of the `bone` attached to `root` has changed accordingly.
    /// posture.append_rotation(root, UnitQuaternion::from_euler_angles(0.0, 0.0, PI / 2.0));
    ///
    /// posture.write_globals(&skelly, &Isometry3::identity(), &mut globals);
    /// let bone_global_new = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space after root rotation at (0, 1, 0).
    /// assert!((bone_global_new.translation.vector - Vector3::y()).magnitude() < EPSILON);
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    #[track_caller]
    pub fn append_rotation(&mut self, bone: usize, rotation: UnitQuaternion<T>)
    where
        T: RealField,
    {
        self.joints[bone].rotation *= rotation
    }

    /// Rotates bone with specified id.
    ///
    /// *Does not* affect relative position to the parent and global position for root bones.
    /// Affects global position of all descendant bones.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::{Skelly, Posture}, na::{Point3, Isometry3, UnitQuaternion, Vector3}, core::f32::{consts::PI, EPSILON}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut posture = Posture::new(&skelly);
    ///
    /// let mut globals = [Isometry3::identity(); 2];
    /// posture.write_globals(&skelly, &Isometry3::identity(), &mut globals);
    /// let bone_global_old = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at (1, 0, 0).
    /// assert!((bone_global_old.translation.vector - Vector3::x()).magnitude() < EPSILON);
    ///
    /// // Rotate the bone. It is still at origin.
    /// // Yet global position of the `bone` attached to `root` has changed accordingly.
    /// posture.prepend_rotation(bone, UnitQuaternion::from_euler_angles(0.0, 0.0, PI / 2.0));
    ///
    /// posture.write_globals(&skelly, &Isometry3::identity(), &mut globals);
    /// let bone_global_new = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space after root rotation at (0, 1, 0).
    /// assert!((bone_global_new.translation.vector - Vector3::y()).magnitude() < EPSILON);
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    #[track_caller]
    pub fn prepend_rotation(&mut self, bone: usize, rotation: UnitQuaternion<T>)
    where
        T: RealField,
    {
        let my_isometry = &mut self.joints[bone];
        *my_isometry = rotation * *my_isometry;
    }

    /// Translates bone with specified id.
    ///
    /// Affects relative position to the parent and global position for root bones.
    /// Affects global position of all descendant bones.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::{Skelly, Posture}, na::{Point3, Isometry3, UnitQuaternion, Vector3}, core::f32::{consts::PI, EPSILON}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut posture = Posture::new(&skelly);
    ///
    /// let mut globals = [Isometry3::identity(); 2];
    /// posture.write_globals(&skelly, &Isometry3::identity(), &mut globals);
    /// let bone_global_old = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at (1, 0, 0).
    /// assert!((bone_global_old.translation.vector - Vector3::x()).magnitude() < EPSILON);
    ///
    /// // Translate root bone.
    /// // Global position of the `bone` attached to `root` has changed accordingly.
    /// posture.append_translation(root, Vector3::z().into());
    ///
    /// posture.write_globals(&skelly, &Isometry3::identity(), &mut globals);
    /// let bone_global_new = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space after root translation at (1, 0, 1).
    /// assert!((bone_global_new.translation.vector - (Vector3::x() + Vector3::z())).magnitude() < EPSILON);
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    #[track_caller]
    pub fn append_translation(&mut self, bone: usize, translation: Translation3<T>)
    where
        T: RealField,
    {
        self.joints[bone].translation *= translation;
    }

    /// Sets relative position for bone with specified id.
    /// Affects global position of all descendant bones.
    ///
    /// This method ignores current relative position of the bone.
    /// To apply translation to current relative poistion see [`Skelly::append_translation`].
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::{Skelly, Posture}, na::{Point3, Isometry3, UnitQuaternion, Vector3}, core::f32::{consts::PI, EPSILON}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut posture = Posture::new(&skelly);
    ///
    /// let mut globals = [Isometry3::identity(); 2];
    /// posture.write_globals(&skelly, &Isometry3::identity(), &mut globals);
    /// let bone_global_old = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at (1, 0, 0).
    /// assert!((bone_global_old.translation.vector - Vector3::x()).magnitude() < EPSILON);
    ///
    /// // Set new relative position for the `bone`.
    /// posture.set_position(bone, Vector3::z());
    ///
    /// posture.write_globals(&skelly, &Isometry3::identity(), &mut globals);
    /// let bone_global_new = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at new position (0, 0, 1).
    /// assert!((bone_global_new.translation.vector - Vector3::z()).magnitude() < EPSILON);
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    #[track_caller]
    pub fn set_position(&mut self, bone: usize, position: Vector3<T>) {
        self.joints[bone].translation = position.into();
    }

    /// Returns current bone position relative to parent.
    #[track_caller]
    pub fn get_position(&mut self, bone: usize) -> Vector3<T>
    where
        T: RealField,
    {
        self.joints[bone].translation.vector
    }

    /// Sets relative orientation for bone with specified id.
    /// Affects global position of all descendant bones.
    ///
    /// This method ignores current relative position of the bone.
    /// To apply translation to current relative poistion see [`Skelly::append_translation`].
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::{Skelly, Posture}, na::{Point3, Isometry3, UnitQuaternion, Vector3}, core::f32::{consts::PI, EPSILON}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut posture = Posture::new(&skelly);
    ///
    /// let mut globals = [Isometry3::identity(); 2];
    /// posture.write_globals(&skelly, &Isometry3::identity(), &mut globals);
    /// let bone_global_old = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at (1, 0, 0).
    /// assert!((bone_global_old.translation.vector - Vector3::x()).magnitude() < EPSILON);
    ///
    /// // Set new relative orientation for the `bone`.
    /// posture.set_orientation(root, UnitQuaternion::from_euler_angles(0.0, 0.0, PI / 2.0));
    ///
    /// posture.write_globals(&skelly, &Isometry3::identity(), &mut globals);
    /// let bone_global_new = globals[bone];
    ///
    /// // Ensure that bone is placed correctly in global space at new position (0, 0, 1).
    /// assert!((bone_global_new.translation.vector - Vector3::y()).magnitude() < EPSILON);
    /// ```
    ///
    /// # Panics
    ///
    /// This method panics if `bone` index is out of bounds.
    #[track_caller]
    pub fn set_orientation(&mut self, bone: usize, orientation: UnitQuaternion<T>) {
        self.joints[bone].rotation = orientation;
    }

    /// Returns current bone orientation relative to parent.
    #[track_caller]
    pub fn get_orientation(&mut self, bone: usize) -> UnitQuaternion<T>
    where
        T: RealField,
    {
        self.joints[bone].rotation
    }

    /// Returns current bone isometry relative to parent.
    #[track_caller]
    pub fn get_isometry(&mut self, bone: usize) -> Isometry3<T>
    where
        T: RealField,
    {
        self.joints[bone]
    }

    /// Fills slice of `Isometry3` with global isometries
    /// for each bone of the `skelly` in this posture.
    ///
    /// # Example
    ///
    /// ```
    /// # use {skelly::{Skelly, Posture}, na::{Point3, Vector3, Isometry3}};
    /// let mut skelly = Skelly::<f32>::new();
    /// let root = skelly.add_root(Point3::origin());
    /// let bone = skelly.attach(Vector3::x(), root);
    ///
    /// let mut posture = Posture::new(&skelly);
    ///
    /// // Animate the skelly by modifying posture iteratively.
    ///
    /// let mut globals = [Isometry3::identity(); 2];
    /// posture.write_globals(&skelly, &Isometry3::identity(), &mut globals);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if this posture is not compatible with the `skelly`.\
    /// To check for compatibility use [`Posture::is_compatible`].\
    /// One may use [`Posture`] with [`Skelly`] used to create that [`Posture`]
    /// (see [`Posture::new`]) as it is guaranteed to be compatible
    /// until new bone is added.
    pub fn write_globals<D>(
        &self,
        skelly: &Skelly<T, D>,
        skelly_global: &Isometry3<T>,
        globals: &mut [Isometry3<T>],
    ) where
        T: RealField,
    {
        assert_eq!(
            self.joints.len(),
            skelly.len(),
            "Posture is not compatible with the skelly"
        );

        self.joints
            .iter()
            .zip(&skelly.bones)
            .take(globals.len())
            .enumerate()
            .for_each(|(index, (isometry, bone))| match bone.parent {
                Some(parent) => {
                    debug_assert!(parent < index);
                    globals[index] = globals[parent] * *isometry;
                }
                None => {
                    globals[index] = skelly_global * *isometry;
                }
            })
    }
}