1use super::{Binding, playback as p};
5use crate::ngui::{Object, V, pair, pptr, st, vector};
6use crate::scene3d::{Layout, game_object, set, transform, xyz};
7
8pub const BONES: [(usize, &str); 15] = [
11 (0, "Hips"),
12 (1, "LeftUpperLeg"),
13 (2, "RightUpperLeg"),
14 (3, "LeftLowerLeg"),
15 (4, "RightLowerLeg"),
16 (5, "LeftFoot"),
17 (6, "RightFoot"),
18 (7, "Spine"),
19 (10, "Head"),
20 (13, "LeftUpperArm"),
21 (14, "RightUpperArm"),
22 (15, "LeftLowerArm"),
23 (16, "RightLowerArm"),
24 (17, "LeftHand"),
25 (18, "RightHand"),
26];
27
28pub const OPTIONAL_BONES: [(usize, &str); 10] = [
31 (8, "Chest"),
32 (54, "UpperChest"),
33 (9, "Neck"),
34 (11, "LeftShoulder"),
35 (12, "RightShoulder"),
36 (19, "LeftToes"),
37 (20, "RightToes"),
38 (21, "LeftEye"),
39 (22, "RightEye"),
40 (23, "Jaw"),
41];
42
43pub const ANIMATOR: i64 = 200;
45pub const AVATAR: i64 = 201;
46pub const CONTROLLER: i64 = 202;
47pub const CLIP: i64 = 203;
48
49#[derive(Clone, Debug)]
51#[allow(
52 clippy::struct_excessive_bools,
53 reason = "independent fixture switches"
54)]
55pub struct Rig {
56 pub twist: [f32; 4],
57 pub stretch: [f32; 3],
58 pub translation_dof: bool,
59 pub root_motion_bone: i32,
60 pub unmapped_bone: Option<usize>,
62 pub no_axes: Option<usize>,
64 pub no_tos: Option<usize>,
66 pub renamed: Option<usize>,
68 pub transform_hierarchy: bool,
69 pub avatar: bool,
70 pub body_offset: [f32; 3],
72 pub root_offset: bool,
74 pub optional: Vec<usize>,
76 pub bone_mass: Option<Vec<f32>>,
78 pub scale: f32,
80 pub hierarchy: bool,
84 pub armature: Vec<([f32; 3], [f32; 4], f32)>,
88 pub positions: Vec<(usize, [f32; 3])>,
91}
92
93impl Default for Rig {
94 fn default() -> Self {
95 Self {
96 twist: [0.; 4],
97 stretch: [0.; 3],
98 translation_dof: false,
99 root_motion_bone: -1,
100 unmapped_bone: None,
101 no_axes: None,
102 no_tos: None,
103 renamed: None,
104 transform_hierarchy: true,
105 avatar: true,
106 body_offset: [0.; 3],
107 root_offset: false,
108 optional: Vec::new(),
109 bone_mass: None,
110 scale: 1.,
111 hierarchy: false,
112 armature: Vec::new(),
113 positions: Vec::new(),
114 }
115 }
116}
117
118#[must_use]
120pub fn crc32(bytes: &[u8]) -> u32 {
121 let mut crc = !0_u32;
122 for &byte in bytes {
123 crc ^= u32::from(byte);
124 for _ in 0..8 {
125 crc = if crc & 1 == 1 {
126 (crc >> 1) ^ 0xedb8_8320
127 } else {
128 crc >> 1
129 };
130 }
131 }
132 !crc
133}
134
135fn bones(rig: &Rig) -> Vec<(usize, &'static str)> {
137 let mut out = BONES.to_vec();
138 out.extend(
139 rig.optional
140 .iter()
141 .filter_map(|bone| OPTIONAL_BONES.iter().find(|(b, _)| b == bone)),
142 );
143 out
144}
145
146fn rig_parent(rig: &Rig, bones: &[(usize, &str)], bone: usize) -> Option<usize> {
150 if bone == 0 {
151 return None;
152 }
153 if !rig.hierarchy {
154 return Some(0);
155 }
156 let mut up = trait_parent(bones[bone].0);
157 while let Some(b) = up {
158 if let Some(k) = bones.iter().position(|&(other, _)| other == b) {
159 return Some(k);
160 }
161 up = trait_parent(b);
162 }
163 Some(0)
164}
165
166fn path(rig: &Rig, bones: &[(usize, &str)], bone: usize) -> String {
168 let mut names = vec![bones[bone].1];
169 let mut at = bone;
170 while let Some(parent) = rig_parent(rig, bones, at) {
171 names.push(bones[parent].1);
172 at = parent;
173 }
174 let armature: Vec<String> = (0..rig.armature.len())
175 .map(|k| format!("Armature{k}"))
176 .collect();
177 names.extend(armature.iter().rev().map(String::as_str));
178 names.reverse();
179 names.join("/")
180}
181
182const fn slot(bone: usize) -> usize {
184 match bone {
185 0..=8 => bone,
186 54 => 9,
187 _ => bone + 1,
188 }
189}
190
191fn ints(items: impl IntoIterator<Item = i32>) -> V {
192 vector(V::Int(0), items.into_iter().map(V::Int).collect())
193}
194
195fn uints(items: impl IntoIterator<Item = u32>) -> V {
196 vector(V::UInt(0), items.into_iter().map(V::UInt).collect())
197}
198
199fn xform() -> V {
200 xform_at([0.; 3])
201}
202
203fn xform_at(t: [f32; 3]) -> V {
204 st(
205 "xform",
206 vec![
207 ("t", xyz("float3", &t)),
208 ("q", xyz("float4", &[0., 0., 0., 1.])),
209 ("s", xyz("float3", &[1., 1., 1.])),
210 ],
211 )
212}
213
214fn data(value: V) -> V {
215 st("OffsetPtr", vec![("data", value)])
216}
217
218fn axes() -> V {
219 st(
220 "Axes",
221 vec![
222 ("m_PreQ", xyz("float4", &[-0.5, -0.5, 0.5, 0.5])),
223 ("m_PostQ", xyz("float4", &[-0.5, -0.5, 0.5, 0.5])),
224 ("m_Sgn", xyz("float3", &[1., 1., 1.])),
225 (
226 "m_Limit",
227 st(
228 "Limit",
229 vec![
230 ("m_Min", xyz("float3", &[-0.5, -0.5, -0.5])),
231 ("m_Max", xyz("float3", &[0.5, 0.5, 0.5])),
232 ],
233 ),
234 ),
235 ("m_Length", V::Float(0.1)),
236 ("m_Type", V::Int(1)),
237 ],
238 )
239}
240
241fn skeleton(rig: &Rig, axes_rows: bool) -> V {
245 let bones = bones(rig);
246 let nodes = 1 + bones.len();
247 let node = |parent: i32, axes: i32| {
248 st(
249 "Node",
250 vec![("m_ParentId", V::Int(parent)), ("m_AxesId", V::Int(axes))],
251 )
252 };
253 let mut rows = vec![node(-1, -1)];
254 let mut records = Vec::new();
255 for bone in 0..bones.len() {
256 let axes_id = if axes_rows && rig.no_axes != Some(bone) {
257 records.push(axes());
258 i32::try_from(records.len() - 1).unwrap_or_default()
259 } else {
260 -1
261 };
262 rows.push(node(i32::from(bone != 0), axes_id));
263 }
264 let ids = (0..nodes).map(|i| {
265 if i == 0 {
266 0
267 } else {
268 crc32(path(rig, &bones, i - 1).as_bytes())
269 }
270 });
271 data(st(
272 "Skeleton",
273 vec![
274 ("m_Node", vector(node(-1, -1), rows)),
275 ("m_ID", uints(ids)),
276 ("m_AxesArray", vector(axes(), records)),
277 ],
278 ))
279}
280
281fn pose(count: usize) -> V {
282 data(st(
283 "SkeletonPose",
284 vec![("m_X", vector(xform(), vec![xform(); count]))],
285 ))
286}
287
288fn human_bones(rig: &Rig) -> [i32; 25] {
291 let mut index = [-1_i32; 25];
292 for (node, &(bone, _)) in bones(rig).iter().enumerate() {
293 if rig.unmapped_bone != Some(bone) {
294 index[slot(bone)] = i32::try_from(node + 1).unwrap_or_default();
295 }
296 }
297 index
298}
299
300fn bone_mass(rig: &Rig, index: &[i32; 25]) -> V {
304 let masses = rig.bone_mass.clone().unwrap_or_else(|| {
305 let heavy = |(slot, &node): (usize, &i32)| node >= 0 && slot < 22;
306 let mapped = index.iter().enumerate().filter(|&e| heavy(e)).count();
307 #[allow(clippy::cast_precision_loss, reason = "at most 25 slots")]
308 let share = 1. / mapped.max(1) as f32;
309 index
310 .iter()
311 .enumerate()
312 .map(|e| if heavy(e) { share } else { 0. })
313 .collect()
314 });
315 vector(V::Float(0.), masses.into_iter().map(V::Float).collect())
316}
317
318#[must_use]
319pub fn avatar(rig: &Rig) -> Object {
320 let bones = bones(rig);
321 let nodes = 1 + bones.len();
322 let index = human_bones(rig);
323 let hand = || data(st("Hand", vec![("m_HandBoneIndex", ints([-1; 15]))]));
324 let [arm, fore_arm, upper_leg, leg] = rig.twist;
325 let [arm_stretch, leg_stretch, feet] = rig.stretch;
326 let human = data(st(
327 "Human",
328 vec![
329 ("m_RootX", xform_at(rig.body_offset)),
330 ("m_Skeleton", skeleton(rig, true)),
331 ("m_SkeletonPose", pose(nodes)),
332 ("m_LeftHand", hand()),
333 ("m_RightHand", hand()),
334 ("m_HumanBoneIndex", ints(index)),
335 ("m_HumanBoneMass", bone_mass(rig, &index)),
336 ("m_Scale", V::Float(rig.scale)),
337 ("m_ArmTwist", V::Float(arm)),
338 ("m_ForeArmTwist", V::Float(fore_arm)),
339 ("m_UpperLegTwist", V::Float(upper_leg)),
340 ("m_LegTwist", V::Float(leg)),
341 ("m_ArmStretch", V::Float(arm_stretch)),
342 ("m_LegStretch", V::Float(leg_stretch)),
343 ("m_FeetSpacing", V::Float(feet)),
344 ("m_HasLeftHand", V::Bool(false)),
345 ("m_HasRightHand", V::Bool(false)),
346 ("m_HasTDoF", V::Bool(rig.translation_dof)),
347 ],
348 ));
349 let identity = || ints((0..nodes).map(|i| i32::try_from(i).unwrap_or_default()));
350 let mut tos = vec![pair(V::UInt(0), V::Str(Vec::new()))];
351 for bone in 0..bones.len() {
352 if rig.no_tos != Some(bone) {
353 let path = path(rig, &bones, bone);
354 tos.push(pair(
355 V::UInt(crc32(path.as_bytes())),
356 V::Str(path.into_bytes()),
357 ));
358 }
359 }
360 let runtime = st(
361 "AvatarConstant",
362 vec![
363 ("m_AvatarSkeleton", skeleton(rig, false)),
364 ("m_AvatarSkeletonPose", pose(nodes)),
365 ("m_DefaultPose", pose(nodes)),
366 (
367 "m_SkeletonNameIDArray",
368 uints((0..nodes).map(|i| u32::try_from(i).unwrap_or_default())),
369 ),
370 ("m_Human", human),
371 ("m_HumanSkeletonIndexArray", identity()),
372 ("m_HumanSkeletonReverseIndexArray", identity()),
373 ("m_RootMotionBoneIndex", V::Int(rig.root_motion_bone)),
374 ("m_RootMotionBoneX", xform()),
375 (
376 "m_RootMotionSkeleton",
377 data(st(
378 "Skeleton",
379 vec![
380 (
381 "m_Node",
382 vector(
383 st(
384 "Node",
385 vec![("m_ParentId", V::Int(-1)), ("m_AxesId", V::Int(-1))],
386 ),
387 vec![],
388 ),
389 ),
390 ("m_ID", uints([])),
391 ("m_AxesArray", vector(axes(), vec![])),
392 ],
393 )),
394 ),
395 ("m_RootMotionSkeletonPose", pose(0)),
396 ("m_RootMotionSkeletonIndexArray", ints([])),
397 ],
398 );
399 let mut avatar = Object::new(
400 AVATAR,
401 90,
402 st(
403 "Avatar",
404 vec![
405 ("m_Name", V::Str(b"avatar".to_vec())),
406 ("m_Avatar", runtime),
407 ("m_TOS", vector(pair(V::UInt(0), V::Str(Vec::new())), tos)),
408 ],
409 ),
410 );
411 if rig.hierarchy {
412 arrange(rig, &mut avatar.value);
413 }
414 avatar
415}
416
417#[must_use]
419pub const fn trait_parent(bone: usize) -> Option<usize> {
420 Some(match bone {
421 1 | 2 | 7 => 0,
422 3 => 1,
423 4 => 2,
424 5 => 3,
425 6 => 4,
426 8 => 7,
427 54 => 8,
428 9 | 11 | 12 => 54,
429 10 => 9,
430 13 => 11,
431 14 => 12,
432 15 => 13,
433 16 => 14,
434 17 => 15,
435 18 => 16,
436 19 => 5,
437 20 => 6,
438 21..=23 => 10,
439 _ => return None,
440 })
441}
442
443#[must_use]
446pub const fn t_pose(bone: usize) -> [f32; 3] {
447 match bone {
448 0 => [0., 1., 0.],
449 1 => [-0.125, 0.875, 0.],
450 2 => [0.125, 0.875, 0.],
451 3 => [-0.125, 0.5, 0.],
452 4 => [0.125, 0.5, 0.],
453 5 => [-0.125, 0.125, 0.],
454 6 => [0.125, 0.125, 0.],
455 7 => [0., 1.125, 0.],
456 8 => [0., 1.25, 0.],
457 54 => [0., 1.375, 0.],
458 9 => [0., 1.5, 0.],
459 10 => [0., 1.625, 0.],
460 11 => [-0.0625, 1.4375, 0.],
461 12 => [0.0625, 1.4375, 0.],
462 13 => [-0.1875, 1.4375, 0.],
463 14 => [0.1875, 1.4375, 0.],
464 15 => [-0.4375, 1.4375, 0.],
465 16 => [0.4375, 1.4375, 0.],
466 17 => [-0.6875, 1.4375, 0.],
467 18 => [0.6875, 1.4375, 0.],
468 19 => [-0.125, 0., 0.125],
469 20 => [0.125, 0., 0.125],
470 21 => [-0.03125, 1.6875, 0.0625],
471 22 => [0.03125, 1.6875, 0.0625],
472 _ => [0., 1.5625, 0.0625],
473 }
474}
475
476fn field<'v>(value: &'v mut V, path: &[&str]) -> Option<&'v mut V> {
477 path.iter().try_fold(value, |value, name| match value {
478 V::Struct(_, fields) => fields.iter_mut().find(|(f, _)| f == name).map(|f| &mut f.1),
479 _ => None,
480 })
481}
482
483fn rows<'v>(value: &'v mut V, path: &[&str]) -> &'v mut [V] {
484 match field(value, path) {
485 Some(V::Vector(_, _, items)) => items,
486 _ => &mut [],
487 }
488}
489
490fn arrange(rig: &Rig, avatar: &mut V) {
495 let bones: Vec<usize> = bones(rig).iter().map(|&(bone, _)| bone).collect();
496 let node = |bone: usize| bones.iter().position(|&b| b == bone).map(|k| k + 1);
497 let parent = |bone: usize| {
498 let mut up = trait_parent(bone);
499 while let Some(b) = up {
500 if node(b).is_some() {
501 return Some(b);
502 }
503 up = trait_parent(b);
504 }
505 None
506 };
507 let n = bones.len() + 1;
508 let up: Vec<usize> = (0..n)
509 .map(|k| match k.checked_sub(1).and_then(|b| bones.get(b)) {
510 Some(&bone) => parent(bone).and_then(node).unwrap_or(0),
511 None => 0,
512 })
513 .collect();
514 let depth = |mut k: usize| {
515 let mut d = 0;
516 while k != 0 && d < n {
517 k = up[k];
518 d += 1;
519 }
520 d
521 };
522 let mut order: Vec<usize> = (0..n).collect();
523 order.sort_by_key(|&k| (depth(k), k));
524 let mut moved = vec![0; n];
525 for (new, &old) in order.iter().enumerate() {
526 moved[old] = new;
527 }
528 let human = ["m_Avatar", "m_Human", "data"];
529 let at = |tail: &[&'static str]| [&human[..], tail].concat();
530 let permute = |items: &mut [V]| {
531 let old = items.to_vec();
532 for (item, &k) in items.iter_mut().zip(&order) {
533 *item = old[k].clone();
534 }
535 };
536 let place = |bone: usize| {
537 rig.positions
538 .iter()
539 .find(|&&(b, _)| b == bone)
540 .map_or_else(|| t_pose(bone), |&(_, at)| at)
541 };
542 let pose = rows(avatar, &at(&["m_SkeletonPose", "data", "m_X"]));
543 for (k, &bone) in bones.iter().enumerate() {
544 let from = parent(bone).map_or([0.; 3], place);
545 let to = place(bone);
546 if let Some(x) = pose.get_mut(k + 1) {
547 set(x, "t", xyz("float3", &[0, 1, 2].map(|c| to[c] - from[c])));
548 }
549 }
550 permute(pose);
551 let nodes = rows(avatar, &at(&["m_Skeleton", "data", "m_Node"]));
552 for (k, row) in nodes.iter_mut().enumerate().skip(1) {
553 let parent = i32::try_from(moved[up[k]]).unwrap_or_default();
554 set(row, "m_ParentId", V::Int(parent));
555 }
556 permute(nodes);
557 permute(rows(avatar, &at(&["m_Skeleton", "data", "m_ID"])));
558 for slot in rows(avatar, &at(&["m_HumanBoneIndex"])) {
559 if let V::Int(index) = slot
560 && let Ok(old) = usize::try_from(*index)
561 && let Some(&new) = moved.get(old)
562 {
563 *index = i32::try_from(new).unwrap_or_default();
564 }
565 }
566}
567
568#[must_use]
571pub fn prefab(rig: &Rig) -> Vec<Object> {
572 let bones = bones(rig);
573 let mut objects = vec![
574 Object::new(1, 1, game_object(b"rig", &[(0, 101), (0, ANIMATOR)])),
575 Object::new(101, 4, {
576 let first = if rig.armature.is_empty() { 102 } else { 190 };
577 let mut root = transform((0, 1), (0, 0), &[(0, first)], false);
578 if rig.root_offset {
579 set(
580 &mut root,
581 "m_LocalPosition",
582 xyz("Vector3f", &[2., 0.25, -1.]),
583 );
584 }
585 root
586 }),
587 ];
588 for (k, &(position, rotation, scale)) in rig.armature.iter().enumerate() {
589 let id = 90 + i64::try_from(k).unwrap_or_default();
590 let name = format!("Armature{k}");
591 objects.push(Object::new(
592 id,
593 1,
594 game_object(name.as_bytes(), &[(0, id + 100)]),
595 ));
596 let father = if k == 0 { 101 } else { id + 99 };
597 let child = if k + 1 == rig.armature.len() {
598 102
599 } else {
600 id + 101
601 };
602 let mut node = transform((0, id), (0, father), &[(0, child)], false);
603 set(&mut node, "m_LocalPosition", xyz("Vector3f", &position));
604 set(&mut node, "m_LocalRotation", xyz("Quaternionf", &rotation));
605 set(&mut node, "m_LocalScale", xyz("Vector3f", &[scale; 3]));
606 objects.push(Object::new(id + 100, 4, node));
607 }
608 let children = |of: usize| -> Vec<_> {
609 (1..bones.len())
610 .filter(|&i| rig_parent(rig, &bones, i) == Some(of))
611 .map(|i| (0, 102 + i64::try_from(i).unwrap_or_default()))
612 .collect()
613 };
614 for (i, &(_, name)) in bones.iter().enumerate() {
615 let id = 2 + i64::try_from(i).unwrap_or_default();
616 let name = if rig.renamed == Some(i) {
617 b"Renamed".as_slice()
618 } else {
619 name.as_bytes()
620 };
621 objects.push(Object::new(id, 1, game_object(name, &[(0, id + 100)])));
622 let top = if rig.armature.is_empty() {
623 101
624 } else {
625 189 + i64::try_from(rig.armature.len()).unwrap_or_default()
626 };
627 let father = rig_parent(rig, &bones, i).map_or(top, |parent| {
628 102 + i64::try_from(parent).unwrap_or_default()
629 });
630 objects.push(Object::new(
631 id + 100,
632 4,
633 transform((0, id), (0, father), &children(i), false),
634 ));
635 }
636 let mut animator = super::animator(ANIMATOR, (0, CONTROLLER));
637 set(
638 &mut animator.value,
639 "m_GameObject",
640 pptr("GameObject", (0, 1)),
641 );
642 set(
643 &mut animator.value,
644 "m_Avatar",
645 pptr("Avatar", (0, if rig.avatar { AVATAR } else { 0 })),
646 );
647 set(
648 &mut animator.value,
649 "m_HasTransformHierarchy",
650 V::Bool(rig.transform_hierarchy),
651 );
652 objects.push(animator);
653 objects.push(super::controller(CONTROLLER, &[(0, CLIP)], &[0]));
654 if rig.avatar {
655 objects.push(avatar(rig));
656 }
657 objects
658}
659
660#[must_use]
663pub fn clip(dofs: &[u32], settings: &[(&str, V)]) -> Object {
664 clip_with(dofs, &[], settings, 0, &[])
665}
666
667#[must_use]
671pub fn clip_with(
672 dofs: &[u32],
673 transforms: &[u32],
674 settings: &[(&str, V)],
675 streamed: u32,
676 words: &[u32],
677) -> Object {
678 let slots = dofs.len() + 3 * transforms.len();
679 let constants = vec![0_u32; slots.saturating_sub(streamed as usize)];
680 clip_stored(
681 dofs,
682 transforms,
683 settings,
684 p::Storage {
685 interval: [0., 1.],
686 streamed_count: streamed,
687 words,
688 constants: &constants,
689 ..p::Storage::default()
690 },
691 )
692}
693
694#[must_use]
697pub fn clip_stored(
698 dofs: &[u32],
699 transforms: &[u32],
700 settings: &[(&str, V)],
701 storage: p::Storage<'_>,
702) -> Object {
703 let mut object = p::explicit(CLIP, 30., &[]);
704 let mut bindings: Vec<_> = dofs
705 .iter()
706 .map(|&attribute| Binding {
707 class: 95,
708 custom: 8,
709 attribute,
710 ..Binding::default()
711 })
712 .collect();
713 bindings.extend(transforms.iter().map(|&path| Binding {
714 path,
715 class: 4,
716 attribute: 1,
717 ..Binding::default()
718 }));
719 p::add_compiled(&mut object, Layout::Unity2022, &bindings, &[], storage);
720 let mut index = vec![-1_i32; 200];
721 for (slot, &dof) in dofs.iter().enumerate() {
722 if let Some(entry) = usize::try_from(dof).ok().and_then(|dof| index.get_mut(dof)) {
723 *entry = i32::try_from(slot).unwrap_or_default();
724 }
725 }
726 let V::Struct(_, root) = &mut object.value else {
727 return object;
728 };
729 let Some((_, muscle)) = root.iter_mut().find(|(name, _)| name == "m_MuscleClip") else {
730 return object;
731 };
732 set(muscle, "m_IndexArray", ints(index));
733 set(
734 muscle,
735 "m_ValueArrayReferencePose",
736 vector(V::Float(0.), vec![]),
737 );
738 for field in [
739 "m_Mirror",
740 "m_LoopTime",
741 "m_LoopBlend",
742 "m_LoopBlendOrientation",
743 "m_LoopBlendPositionY",
744 "m_LoopBlendPositionXZ",
745 "m_KeepOriginalOrientation",
746 "m_KeepOriginalPositionY",
747 "m_KeepOriginalPositionXZ",
748 "m_HeightFromFeet",
749 ] {
750 set(muscle, field, V::Bool(false));
751 }
752 set(muscle, "m_StartAtOrigin", V::Bool(true));
754 set(
756 muscle,
757 "m_StartX",
758 st(
759 "xform",
760 vec![
761 ("t", xyz("Vector3f", &[0.; 3])),
762 ("q", xyz("Quaternionf", &[0., 0., 0., 1.])),
763 ("s", xyz("Vector3f", &[1.; 3])),
764 ],
765 ),
766 );
767 for field in ["m_CycleOffset", "m_Level", "m_OrientationOffsetY"] {
768 set(muscle, field, V::Float(0.));
769 }
770 for (field, value) in settings {
771 set(muscle, field, value.clone());
772 }
773 object
774}