Skip to main content

unityrs_testkit/fuzz/
anim.rs

1//! Synthetic animated scenes shared by the animation fuzz seeds and harness
2//! tests. The generated bytes are never checked into the repository.
3use super::SceneCase;
4use crate::{
5    env as e,
6    ngui::{Object, V},
7    scene3d::{
8        self as s, Layout,
9        anim::{
10            self as a, Binding,
11            playback::{self as p, Dense, Key, Storage},
12        },
13        mesh as m,
14    },
15};
16
17const PREFAB: &str = "assets/synthetic.prefab";
18const CLIP: &str = "assets/synthetic.anim";
19const CAB: &str = "CAB-synthetic";
20/// The IEEE CRC32 of the bare channel name `bend`, as a built generic morph
21/// binding stores it.
22const BEND_ATTRIBUTE: u32 = 1_339_427_383;
23
24/// `anim_clip` cases: every animated scene, alone and in a bundle, as a
25/// scene (flags 0) and as a prefab sampled on the clip's own schedule with
26/// filtered renderers (flags 7), at meters 0, 1, 16 and 64.
27///
28/// # Panics
29/// If a hand-built synthetic file cannot be encoded.
30#[must_use]
31pub fn anim_clip_cases() -> Vec<(String, SceneCase)> {
32    let mut out = Vec::new();
33    for (name, data, _) in scenes() {
34        for flags in [0, 1, 7] {
35            for meter in [0, 1, 16, 64] {
36                out.push((
37                    format!("{name}-f{flags}-m{meter}"),
38                    SceneCase {
39                        meter,
40                        flags,
41                        profile: Vec::new(),
42                        data: data.clone(),
43                    },
44                ));
45            }
46        }
47    }
48    out
49}
50
51/// `anim_gltf` cases: every animated scene under all-discovered (with and
52/// without a sample-rate override) and explicit clip selection, at meters
53/// 0, 1, 16 and 64.
54///
55/// # Panics
56/// If a hand-built synthetic file cannot be encoded.
57#[must_use]
58pub fn anim_gltf_cases() -> Vec<(String, SceneCase)> {
59    let mut out = Vec::new();
60    for (name, data, file_index) in scenes() {
61        let address = |path_id| format!(r#"{{"file_index":{file_index},"path_id":{path_id}}}"#);
62        let explicit = format!(
63            r#"{{"profile_version":1,"clips":[{{"root":{},"component":{},"clip":{}}}],"sample_rate":5.5}}"#,
64            address(2),
65            address(3),
66            address(9),
67        );
68        for (policy, flags, profile) in [
69            (
70                "all",
71                0,
72                br#"{"profile_version":1,"clips":"all_discovered","sample_rate":4}"#.to_vec(),
73            ),
74            (
75                "prefab",
76                1,
77                br#"{"profile_version":1,"clips":"all_discovered"}"#.to_vec(),
78            ),
79            ("explicit", 3, explicit.into_bytes()),
80        ] {
81            for meter in [0, 1, 16, 64] {
82                out.push((
83                    format!("{name}-{policy}-m{meter}"),
84                    SceneCase {
85                        meter,
86                        flags,
87                        profile: profile.clone(),
88                        data: data.clone(),
89                    },
90                ));
91            }
92        }
93    }
94    out
95}
96
97/// Named scene bytes, plain and bundled, with the depth-first file index of
98/// the animated serialized file.
99fn scenes() -> Vec<(String, Vec<u8>, u32)> {
100    let mut rigs: Vec<(String, Rig, Object, Layout)> = Vec::new();
101    for (name, clip) in clips() {
102        for rig in [Rig::Legacy, Rig::Animator] {
103            rigs.push((
104                format!("{name}-{rig:?}"),
105                rig,
106                clip.clone(),
107                Layout::Unity2022,
108            ));
109        }
110    }
111    for rig in [
112        Rig::Override,
113        Rig::LeafInfo,
114        Rig::Cycle,
115        Rig::Dangling,
116        Rig::Negative,
117    ] {
118        rigs.push((
119            format!("generic-{rig:?}"),
120            rig,
121            generic_clip(Generic::ConstantTrs),
122            Layout::Unity2022,
123        ));
124    }
125    for layout in [Layout::Unity2019, Layout::Unity6000] {
126        rigs.push((
127            format!("bindings-{layout:?}"),
128            Rig::Animator,
129            a::bound_clip(9, layout, &bindings(), &[(0, 9)]),
130            layout,
131        ));
132    }
133    let mut out = Vec::new();
134    for (name, rig, clip, layout) in rigs {
135        let file = s::file(layout, &[], &objects(rig, clip, layout)).expect("synthetic animation");
136        let index = e::serialized(
137            &[CAB],
138            &[e::Obj::asset_bundle(
139                100,
140                e::Bundle {
141                    rows: vec![e::row(PREFAB, (0, 0), (1, 1)), e::row(CLIP, (0, 0), (1, 9))],
142                    ..e::Bundle::default()
143                },
144            )],
145        );
146        let bundle = e::bundle(&[("CAB-index", index), (CAB, file.clone())]);
147        out.push((format!("{name}-file"), file, 0));
148        out.push((format!("{name}-bundle"), bundle, 2));
149    }
150    out
151}
152
153#[derive(Clone, Copy, Debug)]
154enum Rig {
155    Legacy,
156    Animator,
157    Override,
158    LeafInfo,
159    Cycle,
160    Dangling,
161    Negative,
162}
163
164/// A rig root with an animation component and a skinned renderer, and a
165/// child instance sharing the root's blend-shape mesh.
166fn objects(rig: Rig, clip: Object, layout: Layout) -> Vec<Object> {
167    let version = match layout {
168        Layout::Unity2019 => m::MeshVersion::V2019,
169        Layout::Unity6000 => m::MeshVersion::V6000,
170        _ => m::MeshVersion::V2022,
171    };
172    let mut mesh = m::mesh(
173        7,
174        b"mesh",
175        &[[1., 0., 0.], [0., 1., 0.], [0., 0., 0.]],
176        &[0, 1, 2],
177        version,
178    );
179    s::set(
180        &mut mesh.value,
181        "m_Shapes",
182        m::blend_shapes(
183            vec![
184                m::blend_vertex(0, [0.5, 0., 0.], [0.; 3], [0.; 3]),
185                m::blend_vertex(1, [1., 0., 0.], [0.; 3], [0.; 3]),
186            ],
187            vec![
188                m::blend_frame(0, 1, false, false),
189                m::blend_frame(1, 1, false, false),
190            ],
191            vec![m::blend_channel(b"bend", 0, 0, 2)],
192            vec![25., 80.],
193        ),
194    );
195    // A second copy, so legacy lists, overrides and leaf tables hold two.
196    let mut second = clip.clone();
197    second.path_id = 12;
198    let component = match rig {
199        Rig::Legacy => a::legacy(3, (0, 9), &[(0, 9), (0, 12)]),
200        Rig::Dangling => a::legacy(3, (0, 999), &[(0, 9), (0, 999)]),
201        Rig::Negative => a::legacy(3, (-1, 9), &[(-1, 9), (0, 9)]),
202        Rig::Override | Rig::Cycle => a::animator(3, (0, 11)),
203        Rig::Animator | Rig::LeafInfo => a::animator(3, (0, 10)),
204    };
205    let mut objects = vec![
206        Object::new(1, 1, s::game_object(b"root", &[(0, 2), (0, 3), (0, 6)])),
207        Object::new(2, 4, s::transform((0, 1), (0, 0), &[(0, 5)], false)),
208        component,
209        Object::new(4, 1, s::game_object(b"instance", &[(0, 5), (0, 8)])),
210        Object::new(5, 4, s::transform((0, 4), (0, 2), &[], false)),
211        Object::new(
212            6,
213            137,
214            s::skinned_mesh_renderer((0, 1), (0, 7), &[], &[10.]),
215        ),
216        mesh,
217        Object::new(
218            8,
219            137,
220            s::skinned_mesh_renderer((0, 4), (0, 7), &[], &[30.]),
221        ),
222        clip,
223        second,
224    ];
225    match rig {
226        Rig::LeafInfo => objects.push(a::controller_with_leaf_info(
227            10,
228            &[(0, 9), (0, 12)],
229            &[0, 1, 7],
230            Some((&[5, 0], 1)),
231        )),
232        Rig::Cycle => objects.push(a::overrides(11, (0, 11), &[((0, 9), (0, 12))])),
233        Rig::Override => {
234            objects.push(a::controller(10, &[(0, 12), (0, 9)], &[0, 1]));
235            objects.push(a::overrides(11, (0, 10), &[((0, 12), (0, 9))]));
236        }
237        _ => objects.push(a::controller(10, &[(0, 9)], &[0])),
238    }
239    objects
240}
241
242/// Every clip layout the testkit builds, each as object 9.
243fn clips() -> Vec<(&'static str, Object)> {
244    let packed = |slopes| {
245        let mut clip = legacy_clip();
246        s::set(&mut clip.value, "m_Compressed", V::Bool(true));
247        s::set(
248            &mut clip.value,
249            "m_CompressedRotationCurves",
250            p::one_row(p::packed_row(slopes)),
251        );
252        clip
253    };
254    let mut nan = generic_clip(Generic::ConstantTrs);
255    let mut words = Vec::new();
256    p::frame(&mut words, f32::MIN, &[]);
257    p::frame(&mut words, f32::NAN, &[(0, [0, 0, 0, u32::MAX])]);
258    p::frame(&mut words, f32::INFINITY, &[]);
259    p::add_compiled(
260        &mut nan,
261        Layout::Unity2022,
262        &bindings(),
263        &[(0, 9)],
264        Storage {
265            interval: [f32::NAN, 3.],
266            streamed_count: u32::MAX,
267            words: &words,
268            dense: Dense {
269                frames: i32::MAX,
270                curves: 5,
271                rate: 0.,
272                begin: f32::INFINITY,
273                bits: &[0; 5],
274            },
275            constants: &[0; 3],
276            discrete_count: None,
277        },
278    );
279    let mut out = vec![
280        ("legacy", legacy_clip()),
281        ("constant", generic_clip(Generic::ConstantTrs)),
282        ("clamped", generic_clip(Generic::ClampedTranslation)),
283        ("flip", generic_clip(Generic::HeldQuaternionFlip)),
284        ("explicit", p::explicit_fixture()),
285        ("compiled", p::compiled_fixture()),
286        ("replay", p::explicit_replay()),
287        ("dense", p::dense_replay()),
288        ("packed", packed(false)),
289        ("slopes", packed(true)),
290        ("metadata", a::clip(9)),
291        ("hostile", nan),
292    ];
293    for (_, clip) in &mut out {
294        clip.path_id = 9;
295    }
296    out
297}
298
299/// A transform position, a generic morph, an unknown class and a `PPtr` curve.
300fn bindings() -> [Binding; 4] {
301    [
302        Binding {
303            class: 4,
304            attribute: 1,
305            ..Binding::default()
306        },
307        Binding {
308            class: 137,
309            custom: 20,
310            attribute: BEND_ATTRIBUTE,
311            ..Binding::default()
312        },
313        Binding {
314            class: 999,
315            attribute: 7,
316            path: 1,
317            ..Binding::default()
318        },
319        Binding {
320            class: 137,
321            pptr: 1,
322            attribute: 3,
323            ..Binding::default()
324        },
325    ]
326}
327
328/// Legacy float, position and rotation curves, with infinite tangents.
329fn legacy_clip() -> Object {
330    let mut left = Key::new(2., [12.5]);
331    left.outgoing = [f32::INFINITY];
332    let mut middle = Key::new(2.25, [17.5]);
333    middle.outgoing = [f32::INFINITY];
334    let right = Key::new(3., [17.5]);
335    let float =
336        |keys: &[Key<1>], attribute| p::curve("", keys, [2, 2], None, true, Some(attribute));
337    p::explicit(
338        9,
339        4.,
340        &[
341            (
342                "m_FloatCurves",
343                vec![
344                    float(&[left, middle, right], ("blendShape.bend", 137)),
345                    float(&[Key::new(2., [0.5])], ("material.opacity", 23)),
346                ],
347            ),
348            (
349                "m_PositionCurves",
350                vec![p::curve(
351                    "",
352                    &[Key::new(2., [0.; 3]), Key::new(3., [1., -2., 0.])],
353                    [2, 2],
354                    None,
355                    true,
356                    None,
357                )],
358            ),
359            (
360                "m_RotationCurves",
361                vec![p::curve(
362                    "instance",
363                    &[
364                        Key::new(2., [0., 0., 0., 1.]),
365                        Key::new(3., [0., 0., 0.6, 0.8]),
366                    ],
367                    [2, 2],
368                    None,
369                    true,
370                    None,
371                )],
372            ),
373        ],
374    )
375}
376
377#[derive(Clone, Copy)]
378enum Generic {
379    ConstantTrs,
380    ClampedTranslation,
381    HeldQuaternionFlip,
382}
383
384/// A compiled generic clip: a streamed morph weight with constant, clamped
385/// or sign-flipping transform channels.
386fn generic_clip(kind: Generic) -> Object {
387    let clamped = matches!(kind, Generic::ClampedTranslation);
388    let held = matches!(kind, Generic::HeldQuaternionFlip);
389    let mut object = p::explicit(9, 4., &[]);
390    let mut words = Vec::new();
391    p::frame(&mut words, f32::MIN, &[]);
392    for (frame, (time, weight)) in [(2., 12.5_f32), (2.25, 17.5), (3., 17.5)]
393        .into_iter()
394        .enumerate()
395    {
396        let last = frame == 2;
397        if clamped && last {
398            p::frame(&mut words, 2.75, &[(1, [0, 0, 0, 1000_f32.to_bits()])]);
399        }
400        if held && last {
401            p::frame(&mut words, 2.75, &[(4, [0, 0, 0, (-1_f32).to_bits()])]);
402        }
403        let mut keys = vec![(0, [0, 0, 0, weight.to_bits()])];
404        if clamped && frame == 0 {
405            keys.extend([(1, [0, 0, 1_f32.to_bits(), 0]), (2, [0; 4]), (3, [0; 4])]);
406        }
407        if held {
408            let w = if time < 2.75 { 1_f32 } else { -1. };
409            keys.extend([
410                (1, [0; 4]),
411                (2, [0; 4]),
412                (3, [0; 4]),
413                (4, [0, 0, 0, w.to_bits()]),
414            ]);
415        }
416        p::frame(&mut words, time, &keys);
417    }
418    p::frame(&mut words, f32::INFINITY, &[]);
419    let (attributes, streamed_count, constants): (_, _, &[f32]) = match kind {
420        Generic::ConstantTrs => ([1, 2], 1, &[1., -2., 0., 0., 0., 0., 1.]),
421        Generic::ClampedTranslation => ([1, 2], 4, &[0., 0., 0., 1.]),
422        Generic::HeldQuaternionFlip => ([2, 1], 5, &[1., -2., 0.]),
423    };
424    let constants: Vec<u32> = constants.iter().map(|x| x.to_bits()).collect();
425    let transform = |attribute| Binding {
426        class: 4,
427        attribute,
428        ..Binding::default()
429    };
430    p::add_compiled(
431        &mut object,
432        Layout::Unity2022,
433        &[
434            Binding {
435                class: 137,
436                custom: 20,
437                attribute: BEND_ATTRIBUTE,
438                ..Binding::default()
439            },
440            transform(attributes[0]),
441            transform(attributes[1]),
442        ],
443        &[],
444        Storage {
445            interval: [2., 3.],
446            streamed_count,
447            words: &words,
448            constants: &constants,
449            ..Storage::default()
450        },
451    );
452    object
453}