Skip to main content

re_core/
ops.rs

1//! High-level operations on a [`Project`]. This is the single API surface
2//! shared by CLI, MCP server and GUI.
3
4use crate::animation::{Animation, Channel, ChannelPath, KeyValue, Space, Target};
5
6/// Upper bound for one paint operation (fill_rect, paint_line): keeps a
7/// bogus coordinate range from an agent or file from allocating without
8/// bound. Generous for real tilemaps (1000×1000 cells).
9pub const MAX_PAINT_CELLS: usize = 1_000_000;
10use crate::id::{AnimationId, MaterialId, MeshId, NodeId, SkeletonId, TileMapId, TileSetId};
11use crate::mesh::Skin;
12use crate::primitives::{self, PrimitiveKind};
13use crate::project::Project;
14use crate::scene::{Node, NodeKind};
15use crate::skeleton::Skeleton;
16use crate::transform::Transform;
17use anyhow::{anyhow, bail, Context, Result};
18use glam::{Mat4, Vec3};
19use std::collections::HashMap;
20
21/// Per-joint local-transform overrides produced by animating a skeleton.
22#[derive(Clone, Debug, Default)]
23pub struct Pose {
24    /// joint index -> animated local transform
25    pub joints: HashMap<usize, Transform>,
26    /// animated transform of the skeleton instance node itself
27    pub node_override: Option<Transform>,
28}
29
30// ---------------------------------------------------------------- nodes
31
32pub fn add_node(
33    p: &mut Project,
34    parent: Option<NodeId>,
35    name: &str,
36    transform: Transform,
37    kind: NodeKind,
38) -> NodeId {
39    p.scene.insert(
40        parent,
41        Node {
42            name: name.to_string(),
43            transform,
44            kind,
45            ..Default::default()
46        },
47    )
48}
49
50// Die Primitive-Bauer halten ihre Parameter flach (Name, Maße, Segmente,
51// Transform, Material) — das hält die RPC-Formate der Capabilities
52// eins zu eins abbildbar, ein Params-Struct würde hier nur Rauschen bauen.
53#[allow(clippy::too_many_arguments)]
54pub fn add_primitive(
55    p: &mut Project,
56    parent: Option<NodeId>,
57    name: &str,
58    kind: PrimitiveKind,
59    a: f32,
60    b: f32,
61    segments: u32,
62    transform: Transform,
63) -> (NodeId, MeshId) {
64    add_primitive_with_material(p, parent, name, kind, a, b, segments, transform, None)
65}
66
67/// Like [`add_primitive`], but immediately assigns a material to the instance.
68#[allow(clippy::too_many_arguments)]
69pub fn add_primitive_with_material(
70    p: &mut Project,
71    parent: Option<NodeId>,
72    name: &str,
73    kind: PrimitiveKind,
74    a: f32,
75    b: f32,
76    segments: u32,
77    transform: Transform,
78    material: Option<MaterialId>,
79) -> (NodeId, MeshId) {
80    let mut mesh = primitives::generate(kind, a, b, segments);
81    if mesh.normals.is_none() {
82        mesh.compute_normals();
83    }
84    let mesh_id = p.library.add_mesh(mesh);
85    let node = add_node(
86        p,
87        parent,
88        name,
89        transform,
90        NodeKind::MeshInstance {
91            mesh: mesh_id,
92            material,
93            skeleton_node: None,
94        },
95    );
96    (node, mesh_id)
97}
98
99/// Attach a material to an existing mesh instance node.
100pub fn set_node_material(
101    p: &mut Project,
102    node: NodeId,
103    material: Option<MaterialId>,
104) -> Result<()> {
105    let n = p.scene.get_mut(node).context("node not found")?;
106    match &mut n.kind {
107        NodeKind::MeshInstance { material: slot, .. } => {
108            *slot = material;
109            Ok(())
110        }
111        _ => bail!("node {node} is not a mesh instance"),
112    }
113}
114
115pub fn set_transform(p: &mut Project, node: NodeId, t: Transform) -> Result<()> {
116    let n = p.scene.get_mut(node).context("node not found")?;
117    n.transform = t;
118    Ok(())
119}
120
121pub fn get_transform(p: &Project, node: NodeId) -> Result<Transform> {
122    p.scene
123        .get(node)
124        .map(|n| n.transform)
125        .context("node not found")
126}
127
128pub fn world_transform(p: &Project, node: NodeId) -> Transform {
129    p.scene.world_transform(node)
130}
131
132// ------------------------------------------------------------- skeletons
133
134pub fn add_skeleton_instance(
135    p: &mut Project,
136    parent: Option<NodeId>,
137    name: &str,
138    skeleton: SkeletonId,
139    transform: Transform,
140) -> Result<NodeId> {
141    p.library
142        .skeletons
143        .get(&skeleton)
144        .context("skeleton asset not found")?;
145    Ok(add_node(
146        p,
147        parent,
148        name,
149        transform,
150        NodeKind::SkeletonInstance { skeleton },
151    ))
152}
153
154pub fn add_humanoid(p: &mut Project, parent: Option<NodeId>, name: &str) -> (NodeId, SkeletonId) {
155    let skel = Skeleton::humanoid(format!("{name} rig"));
156    let skel_id = p.library.add_skeleton(skel);
157    let node = add_node(
158        p,
159        parent,
160        name,
161        Transform::default(),
162        NodeKind::SkeletonInstance { skeleton: skel_id },
163    );
164    (node, skel_id)
165}
166
167pub fn add_joint(
168    p: &mut Project,
169    skeleton: SkeletonId,
170    parent_joint: Option<usize>,
171    name: &str,
172    local: Transform,
173) -> Result<usize> {
174    let sk = p
175        .library
176        .skeletons
177        .get_mut(&skeleton)
178        .context("skeleton asset not found")?;
179    if sk.joint_by_name(name).is_some() {
180        bail!("joint '{name}' already exists in skeleton '{}'", sk.name);
181    }
182    Ok(sk.add_joint(name, parent_joint, local))
183}
184
185/// World-space bind-pose position of a joint of a skeleton instance node.
186pub fn joint_world_position(p: &Project, skel_node: NodeId, joint: usize) -> Vec3 {
187    let base = p.scene.world_transform(skel_node).to_mat4();
188    let global = p
189        .library
190        .skeletons
191        .get(&skeleton_of(p, skel_node).unwrap_or(SkeletonId(u32::MAX)))
192        .map(|s| s.global_transform(joint))
193        .unwrap_or_default();
194    (base * global.to_mat4()).transform_point3(Vec3::ZERO)
195}
196
197/// Skeleton asset referenced by a skeleton-instance node.
198pub fn skeleton_of(p: &Project, skel_node: NodeId) -> Option<SkeletonId> {
199    match p.scene.get(skel_node).map(|n| &n.kind) {
200        Some(NodeKind::SkeletonInstance { skeleton }) => Some(*skeleton),
201        _ => None,
202    }
203}
204
205// ---------------------------------------------------------------- skinning
206
207/// Bind a mesh instance to a skeleton instance with automatic weights:
208/// each vertex is influenced by its two nearest joints with distance falloff.
209///
210/// Assumes mesh and skeleton share the rest pose (typical when the mesh was
211/// modelled around the rig).
212pub fn auto_bind(p: &mut Project, mesh_node: NodeId, skel_node: NodeId) -> Result<()> {
213    let skel_id = skeleton_of(p, skel_node)
214        .ok_or_else(|| anyhow!("node {} is not a skeleton instance", skel_node))?;
215    let mesh_id = match p.scene.get(mesh_node).map(|n| &n.kind) {
216        Some(NodeKind::MeshInstance { mesh, .. }) => *mesh,
217        _ => bail!("node {} is not a mesh instance", mesh_node),
218    };
219
220    let skeleton = p
221        .library
222        .skeletons
223        .get(&skel_id)
224        .context("skeleton asset missing")?
225        .clone();
226
227    // joint positions in mesh-local space
228    let mesh_world = p.scene.world_transform(mesh_node).to_mat4();
229    let mesh_world_inv = mesh_world.inverse();
230    let skel_base = p.scene.world_transform(skel_node).to_mat4();
231    let joint_local: Vec<Vec3> = (0..skeleton.joints.len())
232        .map(|j| {
233            (mesh_world_inv * skel_base * skeleton.global_transform(j).to_mat4())
234                .transform_point3(Vec3::ZERO)
235        })
236        .collect();
237
238    let mesh = p
239        .library
240        .meshes
241        .get_mut(&mesh_id)
242        .context("mesh asset missing")?;
243    let mut joints = Vec::with_capacity(mesh.positions.len());
244    let mut weights = Vec::with_capacity(mesh.positions.len());
245
246    for pos in &mesh.positions {
247        let v = Vec3::from_array(*pos);
248        let mut best: [(f32, usize); 2] = [(f32::MAX, 0), (f32::MAX, 0)];
249        for (ji, jp) in joint_local.iter().enumerate() {
250            let d = v.distance(*jp);
251            if d < best[0].0 {
252                best[1] = best[0];
253                best[0] = (d, ji);
254            } else if d < best[1].0 {
255                best[1] = (d, ji);
256            }
257        }
258        let (d0, j0) = best[0];
259        let (d1, j1) = best[1];
260        let w0 = if d0 + d1 > 1e-6 {
261            1.0 - d0 / (d0 + d1)
262        } else {
263            1.0
264        };
265        let w1 = 1.0 - w0;
266        joints.push([j0 as u16, j1 as u16, 0, 0]);
267        weights.push([w0, w1, 0.0, 0.0]);
268    }
269
270    if let Some(skin) = &mut mesh.skin {
271        skin.joints = joints;
272        skin.weights = weights;
273        skin.skeleton = skel_id;
274    } else {
275        mesh.skin = Some(Skin {
276            skeleton: skel_id,
277            joints,
278            weights,
279        });
280    }
281    mesh.touch();
282    // remember the binding on the node too
283    if let Some(NodeKind::MeshInstance { skeleton_node, .. }) =
284        p.scene.get_mut(mesh_node).map(|n| &mut n.kind)
285    {
286        *skeleton_node = Some(skel_node);
287    }
288    Ok(())
289}
290
291// --------------------------------------------------------------- animation
292
293pub fn add_keyframe_joint(
294    p: &mut Project,
295    anim: AnimationId,
296    joint_name: &str,
297    path: ChannelPath,
298    time: f32,
299    value: KeyValue,
300) -> Result<()> {
301    let a = p
302        .library
303        .animations
304        .get_mut(&anim)
305        .context("animation not found")?;
306    a.get_or_create(Target::Joint(joint_name.to_string()), path)
307        .set_key(time, value);
308    Ok(())
309}
310
311pub fn add_keyframe_node(
312    p: &mut Project,
313    anim: AnimationId,
314    node: NodeId,
315    path: ChannelPath,
316    time: f32,
317    value: KeyValue,
318) -> Result<()> {
319    let a = p
320        .library
321        .animations
322        .get_mut(&anim)
323        .context("animation not found")?;
324    a.get_or_create(Target::Node(node), path)
325        .set_key(time, value);
326    Ok(())
327}
328
329/// Sample `anim` at time `t` and resolve joint-name targets against the
330/// skeleton instance `skel_node` (retargeting). Unknown joint names are skipped.
331pub fn sample_pose(p: &Project, skel_node: NodeId, anim: &Animation, t: f32) -> Pose {
332    let mut pose = Pose::default();
333    let Some(skel_id) = skeleton_of(p, skel_node) else {
334        return pose;
335    };
336    let Some(skeleton) = p.library.skeletons.get(&skel_id) else {
337        return pose;
338    };
339    let apply = |tr: &mut Transform, path: ChannelPath, value: KeyValue| match (path, value) {
340        (ChannelPath::Translation, KeyValue::Vec3(v)) => tr.translation = v,
341        (ChannelPath::Rotation, KeyValue::Quat(q)) => tr.rotation = q,
342        (ChannelPath::Scale, KeyValue::Vec3(s)) => tr.scale = s,
343        _ => {}
344    };
345    // Relative channels compose onto the current value instead of replacing it.
346    let write = |entry: &mut Transform, channel: &Channel, value: KeyValue| {
347        if channel.space == Space::RelativeToBind {
348            let mut delta = Transform::default();
349            apply(&mut delta, channel.path, value);
350            *entry = (*entry).then(&delta);
351        } else {
352            apply(entry, channel.path, value);
353        }
354    };
355    for (channel, value) in anim.sample(t) {
356        match &channel.target {
357            Target::Joint(name) => {
358                if let Some(ji) = skeleton.joint_by_name(name) {
359                    let entry = pose
360                        .joints
361                        .entry(ji)
362                        .or_insert_with(|| skeleton.joints[ji].local);
363                    write(entry, channel, value);
364                }
365            }
366            Target::Node(n) => {
367                if *n == skel_node {
368                    let base = pose.node_override.get_or_insert_with(|| {
369                        p.scene.get(*n).map(|x| x.transform).unwrap_or_default()
370                    });
371                    write(base, channel, value);
372                }
373            }
374        }
375    }
376    pose
377}
378
379/// Effective local transform of a joint given a pose (falls back to bind pose).
380pub fn joint_local(skeleton: &Skeleton, pose: &Pose, joint: usize) -> Transform {
381    pose.joints
382        .get(&joint)
383        .copied()
384        .unwrap_or_else(|| skeleton.joints[joint].local)
385}
386
387/// Global joint transform under a pose (skeleton space).
388pub fn joint_global(skeleton: &Skeleton, pose: &Pose, joint: usize) -> Transform {
389    let local = joint_local(skeleton, pose, joint);
390    match skeleton.joints[joint].parent {
391        Some(parent) => joint_global(skeleton, pose, parent).then(&local),
392        None => local,
393    }
394}
395
396/// World-space skinning matrices (global joint transform, relative to mesh node)
397/// for a mesh bound to `skel_node`, under `pose`.
398///
399/// Each entry is `inv(meshWorld) * skelWorld * jointGlobal_pose(j) * inv(jointGlobal_bind(j))`,
400/// matching glTF skinning semantics: at bind pose the result is the identity.
401pub fn skinning_matrices(
402    p: &Project,
403    mesh_node: NodeId,
404    skel_node: NodeId,
405    pose: &Pose,
406) -> Result<Vec<Mat4>> {
407    let skel_id = skeleton_of(p, skel_node).ok_or_else(|| anyhow!("not a skeleton instance"))?;
408    let skeleton = p
409        .library
410        .skeletons
411        .get(&skel_id)
412        .context("skeleton missing")?;
413    let mesh_world = p.scene.world_transform(mesh_node).to_mat4().inverse();
414    let node_world = p.scene.world_transform(skel_node).to_mat4();
415    Ok((0..skeleton.joints.len())
416        .map(|j| {
417            let posed = joint_global(skeleton, pose, j).to_mat4();
418            let bind_inv = skeleton.global_transform(j).to_mat4().inverse();
419            mesh_world * node_world * posed * bind_inv
420        })
421        .collect())
422}
423
424/// CPU linear blend skinning: returns deformed positions in the mesh node's
425/// local space (apply the mesh node's world transform on top for world space).
426/// Used by the viewer; exporters keep the skin data instead.
427pub fn skinned_positions(
428    p: &Project,
429    mesh_id: MeshId,
430    mesh_node: NodeId,
431    skel_node: NodeId,
432    pose: &Pose,
433) -> Result<Vec<[f32; 3]>> {
434    let mesh = p
435        .library
436        .meshes
437        .get(&mesh_id)
438        .context("mesh missing")?
439        .clone();
440    let skin = mesh.skin.clone().ok_or_else(|| anyhow!("no skin"))?;
441    let mats = skinning_matrices(p, mesh_node, skel_node, pose)?;
442    let mut out = Vec::with_capacity(mesh.positions.len());
443    for (vi, pos) in mesh.positions.iter().enumerate() {
444        let v = Vec3::from_array(*pos);
445        let mut acc = Vec3::ZERO;
446        let w = skin.weights[vi];
447        for (k, &wk) in w.iter().enumerate() {
448            if wk <= 0.0 {
449                continue;
450            }
451            let ji = skin.joints[vi][k] as usize;
452            if ji < mats.len() {
453                acc += mats[ji].transform_point3(v) * wk;
454            }
455        }
456        out.push(acc.to_array());
457    }
458    Ok(out)
459}
460
461/// Create an empty reusable animation asset.
462pub fn create_animation(p: &mut Project, name: &str) -> AnimationId {
463    p.library.add_animation(Animation::new(name))
464}
465
466// ---------------------------------------------------------------- tiles
467
468/// Create an empty tileset with the given cell size (X width, Z depth).
469pub fn create_tileset(p: &mut Project, name: &str, cell_w: f32, cell_d: f32) -> TileSetId {
470    p.library
471        .add_tileset(crate::tileset::TileSet::new(name, cell_w, cell_d))
472}
473
474/// Generate a primitive mesh and register it as a tile. Returns the tile index.
475#[allow(clippy::too_many_arguments)]
476pub fn add_tile_primitive(
477    p: &mut Project,
478    tileset: TileSetId,
479    name: &str,
480    kind: PrimitiveKind,
481    a: f32,
482    b: f32,
483    segments: u32,
484    offset: Transform,
485    material: Option<MaterialId>,
486) -> Result<u32> {
487    if !p.library.tilesets.contains_key(&tileset) {
488        bail!("tileset not found");
489    }
490    let mut mesh = primitives::generate(kind, a, b, segments);
491    if mesh.normals.is_none() {
492        mesh.compute_normals();
493    }
494    let mesh_id = p.library.add_mesh(mesh);
495    let ts = p.library.tilesets.get_mut(&tileset).unwrap();
496    let idx = ts.tiles.len() as u32;
497    ts.tiles.push(crate::tileset::Tile {
498        name: name.to_string(),
499        mesh: mesh_id,
500        offset,
501        material,
502        motion: crate::motion::Motion::None,
503    });
504    Ok(idx)
505}
506
507/// Give one tile a procedural motion (all of its cells animate alike,
508/// phase-staggered per cell in the viewer).
509pub fn set_tile_motion(
510    p: &mut Project,
511    tileset: TileSetId,
512    tile: u32,
513    motion: crate::motion::Motion,
514) -> Result<()> {
515    let ts = p
516        .library
517        .tilesets
518        .get_mut(&tileset)
519        .context("tileset not found")?;
520    let t = ts
521        .tiles
522        .get_mut(tile as usize)
523        .with_context(|| format!("tile {tile} not found"))?;
524    t.motion = motion;
525    Ok(())
526}
527
528/// Register an existing mesh asset as a tile. Returns the tile index.
529pub fn add_tile_mesh(
530    p: &mut Project,
531    tileset: TileSetId,
532    name: &str,
533    mesh: MeshId,
534    offset: Transform,
535    material: Option<MaterialId>,
536) -> Result<u32> {
537    if !p.library.meshes.contains_key(&mesh) {
538        bail!("mesh not found");
539    }
540    let ts = p
541        .library
542        .tilesets
543        .get_mut(&tileset)
544        .context("tileset not found")?;
545    let idx = ts.tiles.len() as u32;
546    ts.tiles.push(crate::tileset::Tile {
547        name: name.to_string(),
548        mesh,
549        offset,
550        material,
551        motion: crate::motion::Motion::None,
552    });
553    Ok(idx)
554}
555
556/// Create a tilemap asset and an instance node for it.
557pub fn create_tilemap(
558    p: &mut Project,
559    name: &str,
560    tileset: TileSetId,
561    parent: Option<NodeId>,
562    transform: Transform,
563) -> Result<(NodeId, TileMapId)> {
564    if !p.library.tilesets.contains_key(&tileset) {
565        bail!("tileset not found");
566    }
567    let map = p
568        .library
569        .add_tilemap(crate::tileset::TileMap::new(name, tileset));
570    let node = add_node(
571        p,
572        parent,
573        name,
574        transform,
575        NodeKind::TileMapInstance { tilemap: map },
576    );
577    Ok((node, map))
578}
579
580fn validate_tile(p: &Project, map: TileMapId, tile: u32) -> Result<()> {
581    let m = p.library.tilemaps.get(&map).context("tilemap not found")?;
582    let ts = p
583        .library
584        .tilesets
585        .get(&m.tileset)
586        .context("tileset not found")?;
587    if tile as usize >= ts.tiles.len() {
588        bail!(
589            "tile {tile} out of range (tileset has {} tiles)",
590            ts.tiles.len()
591        );
592    }
593    Ok(())
594}
595
596/// Paint one cell.
597pub fn tilemap_set_cell(p: &mut Project, map: TileMapId, x: i32, z: i32, tile: u32) -> Result<()> {
598    validate_tile(p, map, tile)?;
599    p.library
600        .tilemaps
601        .get_mut(&map)
602        .context("tilemap not found")?
603        .set(x, z, tile);
604    Ok(())
605}
606
607/// Paint an inclusive rectangle of cells. Returns how many cells were written.
608/// Capped at [`MAX_PAINT_CELLS`] so a bogus range from an agent or file
609/// cannot allocate without bound.
610pub fn tilemap_fill_rect(
611    p: &mut Project,
612    map: TileMapId,
613    x0: i32,
614    z0: i32,
615    x1: i32,
616    z1: i32,
617    tile: u32,
618) -> Result<usize> {
619    validate_tile(p, map, tile)?;
620    let (xa, xb) = (x0.min(x1), x0.max(x1));
621    let (za, zb) = (z0.min(z1), z0.max(z1));
622    let area = (xb as i64 - xa as i64 + 1) * (zb as i64 - za as i64 + 1);
623    if area > MAX_PAINT_CELLS as i64 {
624        bail!("fill_rect would paint {area} cells (limit {MAX_PAINT_CELLS})");
625    }
626    let m = p
627        .library
628        .tilemaps
629        .get_mut(&map)
630        .context("tilemap not found")?;
631    let mut n = 0;
632    for x in xa..=xb {
633        for z in za..=zb {
634            m.set(x, z, tile);
635            n += 1;
636        }
637    }
638    Ok(n)
639}
640
641/// Remove one cell; returns whether anything was there.
642pub fn tilemap_erase(p: &mut Project, map: TileMapId, x: i32, z: i32) -> Result<bool> {
643    Ok(p.library
644        .tilemaps
645        .get_mut(&map)
646        .context("tilemap not found")?
647        .erase(x, z))
648}
649
650/// Remove all cells. Returns the count.
651pub fn tilemap_clear(p: &mut Project, map: TileMapId) -> Result<usize> {
652    Ok(p.library
653        .tilemaps
654        .get_mut(&map)
655        .context("tilemap not found")?
656        .clear())
657}
658
659#[cfg(test)]
660mod tests {
661    use super::*;
662    use crate::animation::{Animation, Channel, KeyValue, Space};
663    use glam::Quat;
664
665    fn project_with_rig() -> (Project, NodeId, SkeletonId) {
666        let mut p = Project::new("t");
667        let mut sk = Skeleton::new("rig");
668        sk.add_joint(
669            "Hips",
670            None,
671            Transform::from_parts(Vec3::new(0.0, 1.0, 0.0), Quat::IDENTITY, Vec3::ONE),
672        );
673        let rig = p.library.add_skeleton(sk);
674        let node = add_node(
675            &mut p,
676            None,
677            "hero",
678            Transform::default(),
679            NodeKind::SkeletonInstance { skeleton: rig },
680        );
681        (p, node, rig)
682    }
683
684    #[test]
685    fn absolute_translation_replaces_bind_offset() {
686        let (mut p, node, _) = project_with_rig();
687        let mut a = Animation::new("clip");
688        let mut ch = Channel::new(Target::Joint("Hips".into()), ChannelPath::Translation);
689        ch.set_key(0.0, KeyValue::Vec3([0.0, 0.1, 0.0]));
690        a.channels.push(ch);
691        let anim = p.library.add_animation(a);
692        let pose = sample_pose(&p, node, p.library.animations.get(&anim).unwrap(), 0.0);
693        // value replaces the local translation -> joint ends up at 0.1, not 1.1
694        assert_eq!(pose.joints[&0].translation, [0.0, 0.1, 0.0]);
695    }
696
697    #[test]
698    fn relative_translation_offsets_from_bind_pose() {
699        let (mut p, node, _) = project_with_rig();
700        let mut a = Animation::new("clip");
701        let mut ch = Channel::new(Target::Joint("Hips".into()), ChannelPath::Translation);
702        ch.space = Space::RelativeToBind;
703        ch.set_key(0.0, KeyValue::Vec3([0.0, 0.1, 0.0]));
704        a.channels.push(ch);
705        let anim = p.library.add_animation(a);
706        let pose = sample_pose(&p, node, p.library.animations.get(&anim).unwrap(), 0.0);
707        assert!((pose.joints[&0].translation[1] - 1.1).abs() < 1e-5);
708    }
709
710    #[test]
711    fn relative_clip_retargets_onto_taller_rig() {
712        // Same clip, two rigs: the bob is relative, so both keep their height.
713        let (mut p, node, rig) = project_with_rig();
714        p.library
715            .skeletons
716            .get_mut(&rig)
717            .unwrap()
718            .joints
719            .iter_mut()
720            .for_each(|j| j.local.translation[0] = 0.0);
721        let mut a = Animation::new("bob");
722        let mut ch = Channel::new(Target::Joint("Hips".into()), ChannelPath::Translation);
723        ch.space = Space::RelativeToBind;
724        ch.set_key(0.0, KeyValue::Vec3([0.0, 0.0, 0.0]));
725        ch.set_key(1.0, KeyValue::Vec3([0.0, 0.2, 0.0]));
726        a.channels.push(ch);
727        let anim = p.library.add_animation(a);
728
729        let far = add_node(
730            &mut p,
731            None,
732            "hero2",
733            Transform::from_parts(Vec3::new(3.0, 0.0, 0.0), Quat::IDENTITY, Vec3::ONE),
734            NodeKind::SkeletonInstance { skeleton: rig },
735        );
736        for (n, expect_x) in [(node, 0.0), (far, 3.0)] {
737            let pose = sample_pose(&p, n, p.library.animations.get(&anim).unwrap(), 1.0);
738            let g = joint_global(p.library.skeletons.get(&rig).unwrap(), &pose, 0);
739            // world position = instance node transform * skeleton-space joint
740            let w = p.scene.world_transform(n).to_mat4() * g.to_mat4();
741            let pos = w.transform_point3(Vec3::ZERO);
742            assert!((pos[1] - 1.2).abs() < 1e-5, "hip height, got {pos:?}");
743            assert!(
744                (pos[0] - expect_x).abs() < 1e-5,
745                "instance offset, got {pos:?}"
746            );
747        }
748    }
749
750    #[test]
751    fn tileset_tilemap_ops_and_validation() {
752        let mut p = Project::new("tiles");
753        let kit = create_tileset(&mut p, "kit", 2.0, 2.0);
754        let floor = add_tile_primitive(
755            &mut p,
756            kit,
757            "floor",
758            PrimitiveKind::Plane,
759            2.0,
760            2.0,
761            1,
762            Transform::default(),
763            None,
764        )
765        .unwrap();
766        assert_eq!(floor, 0);
767        // referencing an unknown mesh must fail
768        let bad = add_tile_mesh(&mut p, kit, "ghost", MeshId(99), Transform::default(), None);
769        assert!(bad.is_err());
770
771        let (node, map) = create_tilemap(&mut p, "field", kit, None, Transform::default()).unwrap();
772        assert_eq!(
773            tilemap_fill_rect(&mut p, map, -1, -1, 1, 1, floor).unwrap(),
774            9
775        );
776        // out-of-range tile index rejected, map stays untouched
777        assert!(tilemap_set_cell(&mut p, map, 5, 5, 7).is_err());
778        assert_eq!(p.library.tilemaps[&map].bounds(), Some((-1, -1, 1, 1)));
779        assert!(matches!(
780            p.scene.get(node).unwrap().kind,
781            NodeKind::TileMapInstance { .. }
782        ));
783
784        // project survives a JSON roundtrip with tiles intact
785        let json = serde_json::to_string(&p).unwrap();
786        let back: Project = serde_json::from_str(&json).unwrap();
787        assert_eq!(back, p);
788    }
789}