Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

42.7 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * Holding an object, on the real engine, against the four things asked of it: a change of what is held does not make a hand jump; the two hands
 * cannot drive each other round a loop; a different body still puts its palm where the object says; and the same inputs give the same bones.
 */
import { afterEach, beforeAll, describe, expect, it } from 'vitest';
import { App } from '../src/app/app';
import { AnimationPlugin } from '../src/animation/AnimationPlugin';
import { SkeletalAnimationPlugin } from '../src/animation/SkeletalAnimationPlugin';
import { GripHand, GripHolder, GripMirror, GripPlacement, GripProfile, captureFingerPose, gripHolderStatus, registerFingerPose, releaseGripHolds, slerpQuat, type GripHolderData, type GripProfileData } from '../src/animation/gripHold';
import { GripPose, gripHandJoints, gripPose, gripPoseByJoint, gripPoseFromJson, gripPoseStatus, palmFrameOf, registerGripPose } from '../src/animation/gripPose';
import { GripSurface, GripSurfaceShape, closeFinger, gripSurfaceLines, surfaceDistance, surfacesUnder } from '../src/animation/gripContact';
import { Children, Name, Parent, Transform, type TransformData } from '../src/ecs/component';
import { setEditorMode, setFxEditPreview, setPlayMode } from '../src/ecs/env';
import { q } from '../src/math/quat';
import type { Entity } from '../src/types';
import type { ESEngineModule } from '../src/wasm';
import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';

interface V { x: number; y: number; z: number }
interface Q { w: number; x: number; y: number; z: number }
const I: Q = { w: 1, x: 0, y: 0, z: 0 };

let core: ESEngineModule;
const apps: App[] = [];
afterEach(() => { while (apps.length) apps.pop()!.quit?.(); setEditorMode(false); setPlayMode(false); setFxEditPreview(false); });

function scene() {
    core.setActiveContext(null);
    const app = App.new(); apps.push(app); app.connectCpp(new core.Registry(), core, { ownedRegistry: true });
    setPlayMode(true);
    app.addPlugin(new AnimationPlugin());
    app.addPlugin(new SkeletalAnimationPlugin());
    const tick = async (n = 1, dt = 1 / 60): Promise<void> => { for (let i = 0; i < n; i++) { await app.tick(dt); await Promise.resolve(); } };
    return { app, world: app.world, tick };
}
type World = App['world'];

const FINGERS: Record<string, { from: V; lengths: number[] }> = {
    Thumb: { from: { x: -0.03, y: 0.02, z: -0.01 }, lengths: [0.035, 0.03, 0.025] },
    Index: { from: { x: -0.025, y: 0.09, z: 0 }, lengths: [0.04, 0.025, 0.02] },
    Middle: { from: { x: -0.005, y: 0.095, z: 0 }, lengths: [0.045, 0.03, 0.02] },
    Ring: { from: { x: 0.015, y: 0.09, z: 0 }, lengths: [0.04, 0.028, 0.02] },
    Pinky: { from: { x: 0.033, y: 0.08, z: 0 }, lengths: [0.03, 0.02, 0.018] },
};

/**
 * A body with two arms reaching forward (+Z) from shoulders 0.2 apart, each ending in a hand whose fingers point along the arm and whose palm faces
 * down. `upper` and `fore` are the arm's two lengths, to try another body with the same object.
 */
function body(world: World, options: { upper?: number; fore?: number } = {}) {
    const upperLen = options.upper ?? 0.3, foreLen = options.fore ?? 0.27;
    const spawn = (name: string, parent: Entity | null, position: V, rotation: Q = I): Entity => {
        const e = world.spawn(name);
        world.insert(e, Name, { value: name });
        world.insert(e, Transform, { position, rotation });
        if (parent !== null) world.setParent(e, parent);
        return e;
    };
    const root = spawn('Hero', null, { x: 0, y: 0, z: 0 });
    const spine = spawn('mixamorig:Spine', root, { x: 0, y: 1.4, z: 0 });
    // Bones along +Y, turned so +Y runs forward: the hand's fingers point ahead, its palm down.
    const forward = q.normalize({ w: Math.SQRT1_2, x: Math.SQRT1_2, y: 0, z: 0 });
    const arms: Record<string, { upper: Entity; fore: Entity; hand: Entity }> = {};
    for (const [side, mirror] of [['Right', -1], ['Left', 1]] as const) {
        const shoulder = spawn(`mixamorig:${side}Shoulder`, spine, { x: 0.2 * mirror, y: 0, z: 0 }, forward);
        // A slight bend down at the elbow, so the arm has a side to bend to.
        const upper = spawn(`mixamorig:${side}Arm`, shoulder, { x: 0, y: 0.05, z: 0 }, q.normalize({ w: 0.999, x: 0.04, y: 0, z: 0 }));
        const fore = spawn(`mixamorig:${side}ForeArm`, upper, { x: 0, y: upperLen, z: 0 }, q.normalize({ w: 0.995, x: -0.1, y: 0, z: 0 }));
        const hand = spawn(`mixamorig:${side}Hand`, fore, { x: 0, y: foreLen, z: 0 });
        for (const [finger, f] of Object.entries(FINGERS)) {
            let parent = hand, at: V = { x: f.from.x * -mirror, y: f.from.y, z: f.from.z };
            let prev: V = { x: 0, y: 0, z: 0 };
            const dir = finger === 'Thumb' ? { x: -0.7 * -mirror, y: 0.7, z: 0 } : { x: 0, y: 1, z: 0 };
            const unit = Math.hypot(dir.x, dir.y, dir.z);
            for (let i = 0; i <= f.lengths.length; i++) {
                parent = spawn(`mixamorig:${side}Hand${finger}${i + 1}`, parent, { x: at.x - prev.x, y: at.y - prev.y, z: at.z - prev.z });
                prev = at;
                if (i < f.lengths.length) at = { x: at.x + dir.x / unit * f.lengths[i]!, y: at.y + dir.y / unit * f.lengths[i]!, z: at.z + dir.z / unit * f.lengths[i]! };
            }
        }
        arms[side] = { upper, fore, hand };
    }
    return { root, arms };
}

/** An object with a leading and a supporting anchor, the second `apart` ahead of the first. */
function gun(world: World, at: V, apart = 0.18, name = 'Gun', across = 0) {
    const e = world.spawn(name);
    world.insert(e, Name, { value: name });
    world.insert(e, Transform, { position: at });
    const anchor = (label: string, p: V, r: Q = I): Entity => {
        const a = world.spawn(label);
        world.insert(a, Name, { value: label });
        world.insert(a, Transform, { position: p, rotation: r });
        world.setParent(a, e);
        return a;
    };
    // Fingers ahead (+Z) and the palm facing down (-Y is the way +Y of the anchor must face here, so turned about Z by half a turn).
    const down = { w: 0, x: 0, y: 0, z: 1 };
    // Off the object's origin, so an anchor read as the object itself is caught.
    const main = anchor('Main', { x: 0.01, y: -0.03, z: -0.02 }, down);
    const support = anchor('Support', { x: across, y: 0.02, z: apart }, down);
    world.insert(e, GripProfile, { mainAnchor: main, supportAnchor: support, mainPose: '', supportPose: '' });
    return { e, main, support };
}

/** A bone's world pose from the locals, so a test does not lean on the engine's own composing. */
function worldPose(world: World, e: Entity): { p: V; r: Q } {
    const chain: Entity[] = [];
    for (let at: Entity | null = e; at !== null;) {
        chain.unshift(at);
        const p = world.tryGet(at, Parent) as { entity?: Entity } | null;
        at = p && typeof p.entity === 'number' ? p.entity : null;
    }
    let p: V = { x: 0, y: 0, z: 0 }, r: Q = I;
    for (const link of chain) {
        const t = world.get(link, Transform) as TransformData;
        const v = q.rotate(r, t.position);
        p = { x: p.x + v.x, y: p.y + v.y, z: p.z + v.z };
        r = q.normalize(q.mul(r, t.rotation));
    }
    return { p, r };
}

function palmOf(world: World, hand: Entity, side: 'right' | 'left') {
    const frame = palmFrameOf(world, hand, side)!;
    const h = worldPose(world, hand);
    const v = q.rotate(h.r, frame.center);
    return { p: { x: h.p.x + v.x, y: h.p.y + v.y, z: h.p.z + v.z }, r: q.normalize(q.mul(h.r, frame.turn)) };
}

const dist = (a: V, b: V): number => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
/** The angle between two turns, by the sine of the half angle: acos of a dot product near 1 turns float32 rounding into a thousandth of a radian. */
const angle = (a: Q, b: Q): number => { const d = q.mul(q.conjugate(a), b); return 2 * Math.atan2(Math.hypot(d.x, d.y, d.z), Math.abs(d.w)); };
const rotationsOf = (world: World, joints: Entity[]): Q[] => joints.map((j) => ({ ...(world.get(j, Transform) as TransformData).rotation }));
const holder = (world: World, root: Entity, data: Partial<GripHolderData>): void => { world.insert(root, GripHolder, { blendSeconds: 0, ...data }); };

/** Puts the supporting anchor where the left arm can reach, read off the object as it now stands: in front of the chest, the palm down. */
function reachable(world: World, g: { e: Entity; support: Entity }, at: V = { x: 0.02, y: 1.38, z: 0.5 }): void {
    const o = worldPose(world, g.e);
    const back = q.conjugate(o.r);
    const local = q.rotate(back, { x: at.x - o.p.x, y: at.y - o.p.y, z: at.z - o.p.z });
    const down = { w: 0, x: 0, y: 0, z: 1 };
    world.update(g.support, Transform, (t: TransformData) => { t.position = local; t.rotation = q.normalize(q.mul(back, q.mul(o.r, q.mul(q.conjugate(o.r), down)))); });
}
const armJoints = (b: ReturnType<typeof body>): Entity[] => Object.values(b.arms).flatMap((a) => [a.upper, a.fore, a.hand]);

describe.skipIf(!HAS_WASM)('holding an object', () => {
    beforeAll(async () => { if (HAS_WASM) core = await loadWasmModule(); });

    it('puts the leading palm on the object\'s anchor when the game places the object', async () => {
        const s = scene();
        const b = body(s.world);
        const g = gun(s.world, { x: -0.15, y: 1.25, z: 0.45 });
        holder(s.world, b.root, { held: g.e, placement: GripPlacement.Object, supportWeight: 0 });
        await s.tick(2);
        const palm = palmOf(s.world, b.arms.Right!.hand, 'right');
        const anchor = worldPose(s.world, g.main);
        expect(dist(palm.p, anchor.p)).toBeLessThan(1e-3);
        expect(angle(palm.r, anchor.r)).toBeLessThan(0.01);
    });

    it('carries the object on the leading hand where the clip has put it, and leaves that hand alone', async () => {
        const s = scene();
        const b = body(s.world);
        const g = gun(s.world, { x: 3, y: 0, z: 0 });
        const before = rotationsOf(s.world, [b.arms.Right!.upper, b.arms.Right!.fore, b.arms.Right!.hand]);
        holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand, supportWeight: 0 });
        await s.tick(2);
        const palm = palmOf(s.world, b.arms.Right!.hand, 'right');
        const anchor = worldPose(s.world, g.main);
        expect(dist(palm.p, anchor.p)).toBeLessThan(1e-3);
        expect(angle(palm.r, anchor.r)).toBeLessThan(0.01);
        const after = rotationsOf(s.world, [b.arms.Right!.upper, b.arms.Right!.fore, b.arms.Right!.hand]);
        after.forEach((r, i) => expect(angle(r, before[i]!)).toBeLessThan(1e-6));
    });

    it('brings the supporting palm to its anchor on the object as it now stands', async () => {
        const s = scene();
        const b = body(s.world);
        const g = gun(s.world, { x: 3, y: 0, z: 0 });
        holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand });
        await s.tick(1);
        reachable(s.world, g);
        await s.tick(2);
        const palm = palmOf(s.world, b.arms.Left!.hand, 'left');
        const anchor = worldPose(s.world, g.support);
        expect(dist(palm.p, anchor.p)).toBeLessThan(1e-3);
    });

    describe('does not make a hand jump when what is held changes', () => {
        it('eases every joint over, each frame a small part of the way', async () => {
            const run = async (blend: number) => {
                const s = scene();
                const b = body(s.world);
                const a = gun(s.world, { x: -0.15, y: 1.25, z: 0.45 }, 0.18, 'A');
                const c = gun(s.world, { x: -0.05, y: 1.1, z: 0.35 }, 0.1, 'B');
                holder(s.world, b.root, { held: a.e, placement: GripPlacement.Object, blendSeconds: blend });
                await s.tick(60);
                const joints = armJoints(b);
                let last = rotationsOf(s.world, joints), biggest = 0, total = 0;
                const start = last;
                s.world.update(b.root, GripHolder, (d: GripHolderData) => { d.held = c.e; });
                for (let i = 0; i < 60; i++) {
                    await s.tick(1);
                    const now = rotationsOf(s.world, joints);
                    biggest = Math.max(biggest, ...now.map((r, k) => angle(r, last[k]!)));
                    last = now;
                }
                total = Math.max(...last.map((r, k) => angle(r, start[k]!)));
                return { biggest, total };
            };
            const eased = await run(0.25), cut = await run(0);
            expect(cut.biggest).toBeCloseTo(cut.total, 3);
            expect(eased.total).toBeCloseTo(cut.total, 3);
            expect(eased.biggest).toBeLessThan(eased.total * 0.15);
        });

        it('takes hold and lets go the same way, back to the clip\'s pose', async () => {
            const s = scene();
            const b = body(s.world);
            const g = gun(s.world, { x: -0.15, y: 1.25, z: 0.45 });
            const joints = armJoints(b);
            const rest = rotationsOf(s.world, joints);
            holder(s.world, b.root, { held: g.e, placement: GripPlacement.Object, blendSeconds: 0.25 });
            let last = rest, biggest = 0;
            for (let i = 0; i < 60; i++) { await s.tick(1); const now = rotationsOf(s.world, joints); biggest = Math.max(biggest, ...now.map((r, k) => angle(r, last[k]!))); last = now; }
            const held = Math.max(...last.map((r, k) => angle(r, rest[k]!)));
            expect(held).toBeGreaterThan(0.2);
            expect(biggest).toBeLessThan(held * 0.15);
            s.world.update(b.root, GripHolder, (d: GripHolderData) => { d.held = 0 as Entity; });
            await s.tick(60);
            rotationsOf(s.world, joints).forEach((r, k) => expect(angle(r, rest[k]!)).toBeLessThan(1e-3));
        });
    });

    describe('cannot drive itself round a loop', () => {
        it('moves neither the object nor the leading arm when the supporting anchor moves', async () => {
            const s = scene();
            const b = body(s.world);
            const g = gun(s.world, { x: 3, y: 0, z: 0 });
            holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand });
            await s.tick(1);
            reachable(s.world, g);
            await s.tick(3);
            const object = worldPose(s.world, g.e), main = rotationsOf(s.world, [b.arms.Right!.upper, b.arms.Right!.fore, b.arms.Right!.hand]);
            reachable(s.world, g, { x: 0.08, y: 1.33, z: 0.45 });
            await s.tick(3);
            const after = worldPose(s.world, g.e);
            expect(dist(after.p, object.p)).toBe(0);
            rotationsOf(s.world, [b.arms.Right!.upper, b.arms.Right!.fore, b.arms.Right!.hand]).forEach((r, k) => expect(r).toEqual(main[k]));
            expect(dist(palmOf(s.world, b.arms.Left!.hand, 'left').p, worldPose(s.world, g.support).p)).toBeLessThan(1e-3);
        });

        it('stays exactly where it settled, frame after frame, with nothing changing', async () => {
            for (const placement of [GripPlacement.Hand, GripPlacement.Object]) {
                const s = scene();
                const b = body(s.world);
                const g = gun(s.world, placement === GripPlacement.Hand ? { x: 3, y: 0, z: 0 } : { x: -0.15, y: 1.25, z: 0.45 });
                holder(s.world, b.root, { held: g.e, placement, blendSeconds: 0.2 });
                await s.tick(90);
                const joints = armJoints(b);
                const settled = rotationsOf(s.world, joints), object = worldPose(s.world, g.e);
                await s.tick(300);
                expect(rotationsOf(s.world, joints)).toEqual(settled);
                expect(worldPose(s.world, g.e)).toEqual(object);
            }
        });
    });

    describe('puts the palm where the object says on another body', () => {
        it('for arms shorter and longer than the one it was made with', async () => {
            for (const [upper, fore] of [[0.24, 0.22], [0.3, 0.27], [0.36, 0.32]]) {
                const s = scene();
                const b = body(s.world, { upper, fore });
                const g = gun(s.world, { x: -0.12, y: 1.32, z: 0.3 }, 0.12, 'Gun', 0.22);
                holder(s.world, b.root, { held: g.e, placement: GripPlacement.Object });
                await s.tick(2);
                for (const [side, hand, anchor] of [['right', b.arms.Right!.hand, g.main], ['left', b.arms.Left!.hand, g.support]] as const) {
                    const palm = palmOf(s.world, hand, side);
                    const at = worldPose(s.world, anchor);
                    expect(dist(palm.p, at.p), `${side} at ${upper}+${fore}`).toBeLessThan(1e-3);
                    expect(angle(palm.r, at.r), `${side} at ${upper}+${fore}`).toBeLessThan(0.01);
                }
            }
        });

        it('out of reach, points the arm straight at the anchor and turns the palm to it, every time the same', async () => {
            const s = scene();
            const b = body(s.world, { upper: 0.2, fore: 0.18 });
            const g = gun(s.world, { x: -0.15, y: 1.25, z: 0.9 });
            holder(s.world, b.root, { held: g.e, placement: GripPlacement.Object, supportWeight: 0 });
            await s.tick(2);
            const shoulder = worldPose(s.world, b.arms.Right!.upper).p, elbow = worldPose(s.world, b.arms.Right!.fore).p, hand = worldPose(s.world, b.arms.Right!.hand).p;
            const anchor = worldPose(s.world, g.main);
            const toward = (from: V, to: V): V => { const d = dist(from, to); return { x: (to.x - from.x) / d, y: (to.y - from.y) / d, z: (to.z - from.z) / d }; };
            const a = toward(shoulder, elbow), c = toward(elbow, hand), goal = toward(shoulder, anchor.p);
            expect(a.x * c.x + a.y * c.y + a.z * c.z).toBeGreaterThan(0.999);
            expect(a.x * goal.x + a.y * goal.y + a.z * goal.z).toBeGreaterThan(0.99);
            expect(angle(palmOf(s.world, b.arms.Right!.hand, 'right').r, anchor.r)).toBeLessThan(0.01);
        });
    });

    it('gives the same bones for the same inputs, to the last bit', async () => {
        const steps = [1 / 60, 1 / 30, 1 / 144, 1 / 60, 1 / 45, 1 / 60, 1 / 90];
        const run = async () => {
            const s = scene();
            const b = body(s.world);
            const a = gun(s.world, { x: -0.15, y: 1.25, z: 0.45 }, 0.18, 'A');
            const c = gun(s.world, { x: -0.05, y: 1.1, z: 0.35 }, 0.1, 'B');
            holder(s.world, b.root, { held: a.e, placement: GripPlacement.Object, blendSeconds: 0.2 });
            for (let i = 0; i < 40; i++) await s.tick(1, steps[i % steps.length]);
            s.world.update(b.root, GripHolder, (d: GripHolderData) => { d.held = c.e; });
            for (let i = 0; i < 20; i++) await s.tick(1, steps[i % steps.length]);
            return [...rotationsOf(s.world, armJoints(b)), ...Object.values(b.arms).flatMap((arm) => rotationsOf(s.world, [arm.hand]))];
        };
        expect(await run()).toEqual(await run());
    });

    it('blends a captured finger pose over the clip by the weight, as slerp(clip, grip, w)', async () => {
        const s = scene();
        const b = body(s.world);
        const finger = s.world.getEntitiesWithComponents([Name]).find((e) => (s.world.get(e, Name) as { value: string }).value === 'mixamorig:RightHandIndex1')!;
        const grip = q.normalize({ w: 0.8, x: 0.5, y: 0.2, z: 0.1 });
        const clip = (s.world.get(finger, Transform) as TransformData).rotation;
        registerFingerPose('test-curl', { joints: { 'mixamorig:RightHandIndex1': grip } });
        const g = gun(s.world, { x: 3, y: 0, z: 0 });
        s.world.update(g.e, GripProfile, (p: { mainPose: string }) => { p.mainPose = 'test-curl'; });
        holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand, weight: 0.5, supportWeight: 0 });
        await s.tick(2);
        const want = slerpQuat(clip, grip, 0.5);
        const got = (s.world.get(finger, Transform) as TransformData).rotation;
        expect(angle(got, want)).toBeLessThan(1e-5);
        expect(gripHolderStatus(s.app, b.root)!.amount).toBe(0.5);
    });

    it('captures a hand\'s fingers as plain JSON that puts them back', async () => {
        const s = scene();
        const b = body(s.world);
        const hand = b.arms.Right!.hand;
        const named = (n: string) => s.world.getEntitiesWithComponents([Name]).find((e) => (s.world.get(e, Name) as { value: string }).value === n)!;
        s.world.update(named('mixamorig:RightHandMiddle2'), Transform, (t: TransformData) => { t.rotation = q.normalize({ w: 0.7, x: 0.7, y: 0, z: 0 }); });
        const pose = JSON.parse(JSON.stringify(captureFingerPose(s.world, hand)));
        expect(Object.keys(pose.joints)).toContain('mixamorig:RightHandMiddle2');
        expect(Object.keys(pose.joints).length).toBe(20);
        registerFingerPose('kept', pose);
        s.world.update(named('mixamorig:RightHandMiddle2'), Transform, (t: TransformData) => { t.rotation = I; });
        const g = gun(s.world, { x: 3, y: 0, z: 0 });
        s.world.update(g.e, GripProfile, (p: { mainPose: string }) => { p.mainPose = 'kept'; });
        holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand, supportWeight: 0 });
        await s.tick(2);
        expect(angle((s.world.get(named('mixamorig:RightHandMiddle2'), Transform) as TransformData).rotation, q.normalize({ w: 0.7, x: 0.7, y: 0, z: 0 }))).toBeLessThan(1e-5);
    });

    it('hands a grip pose by name to the hand\'s GripPose, by the hold\'s weight', async () => {
        const s = scene();
        const b = body(s.world);
        const g = gun(s.world, { x: 3, y: 0, z: 0 });
        s.world.update(g.e, GripProfile, (p: { mainPose: string; supportPose: string }) => { p.mainPose = 'pistol'; p.supportPose = 'support'; });
        holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand });
        await s.tick(3);
        const status = gripPoseStatus(s.app, b.root)!;
        expect(status.right.pose).toBe('pistol');
        expect(status.left.pose).toBe('support');
        expect(status.right.weight).toBe(1);
        // Handed over without writing a GripPose onto the rig: an editor's preview must not leave a component behind.
        expect(s.world.has(b.root, GripPose)).toBe(false);
        // Let go of, the hands fade out and are forgotten once nothing is left of them.
        s.world.update(b.root, GripHolder, (h: GripHolderData) => { h.held = 0 as Entity; });
        await s.tick(3);
        expect(gripPoseStatus(s.app, b.root)).toBeNull();
    });

    it('mirrors the anchors in the object\'s own plane when the other hand leads, so one set serves either hand', async () => {
        const run = async (mainHand: number, x: number) => {
            const s = scene();
            const b = body(s.world);
            const g = gun(s.world, { x, y: 1.25, z: 0.45 });
            // Turned off the gun's own plane (yawed, then rolled), so a mirror that kept the turn would put the palm the wrong way round.
            const tilt = q.normalize(q.mul({ w: Math.cos(0.2), x: 0, y: Math.sin(0.2), z: 0 }, q.mul({ w: Math.cos(0.15), x: 0, y: 0, z: Math.sin(0.15) }, { w: 0, x: 0, y: 0, z: 1 })));
            s.world.update(g.main, Transform, (t: TransformData) => { t.rotation = tilt; });
            holder(s.world, b.root, { held: g.e, placement: GripPlacement.Object, supportWeight: 0, mainHand });
            await s.tick(2);
            return { s, b, g };
        };
        const right = await run(GripHand.Right, -0.15);
        const left = await run(GripHand.Left, 0.15);
        expect(gripHolderStatus(left.s.app, left.b.root)!.mirrored).toBe(true);
        expect(gripHolderStatus(right.s.app, right.b.root)!.mirrored).toBe(false);
        // The left palm sits on the anchor mirrored in the gun's YZ plane: its place with x negated, its turn the mirror of the anchor's.
        const o = worldPose(left.s.world, left.g.e);
        const a = left.s.world.get(left.g.main, Transform) as TransformData;
        const at = q.rotate(o.r, { x: -a.position.x, y: a.position.y, z: a.position.z });
        const want = { p: { x: o.p.x + at.x, y: o.p.y + at.y, z: o.p.z + at.z }, r: q.normalize(q.mul(o.r, { w: a.rotation.w, x: a.rotation.x, y: -a.rotation.y, z: -a.rotation.z })) };
        const palm = palmOf(left.s.world, left.b.arms.Left!.hand, 'left');
        expect(dist(palm.p, want.p)).toBeLessThan(1e-3);
        expect(angle(palm.r, want.r)).toBeLessThan(0.01);
        // And on a body that is its own mirror, the whole left arm is the right one's mirror image.
        const pr = palmOf(right.s.world, right.b.arms.Right!.hand, 'right').p;
        expect(dist(palm.p, { x: -pr.x, y: pr.y, z: pr.z })).toBeLessThan(1e-3);
        const er = worldPose(right.s.world, right.b.arms.Right!.fore).p, el = worldPose(left.s.world, left.b.arms.Left!.fore).p;
        expect(dist(el, { x: -er.x, y: er.y, z: er.z })).toBeLessThan(1e-3);
    });

    it('does not mirror anchors placed for the hand that leads, whichever it is', async () => {
        const s = scene();
        const b = body(s.world);
        const g = gun(s.world, { x: 0.15, y: 1.25, z: 0.45 });
        s.world.update(g.e, GripProfile, (p: { hand: number; mirror: number }) => { p.hand = GripHand.Left; p.mirror = GripMirror.X; });
        holder(s.world, b.root, { held: g.e, placement: GripPlacement.Object, supportWeight: 0, mainHand: GripHand.Left });
        await s.tick(2);
        expect(gripHolderStatus(s.app, b.root)!.mirrored).toBe(false);
        const palm = palmOf(s.world, b.arms.Left!.hand, 'left');
        expect(dist(palm.p, worldPose(s.world, g.main).p)).toBeLessThan(1e-3);
    });

    it('holds fingers said joint by joint exactly as the preset they were expanded from, and one joint changed moves that joint alone', async () => {
        const fingersOf = async (profile: Partial<GripProfileData>) => {
            const s = scene();
            const b = body(s.world);
            const g = gun(s.world, { x: 3, y: 0, z: 0 });
            s.world.update(g.e, GripProfile, (p: GripProfileData) => { Object.assign(p, profile); });
            holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand });
            await s.tick(30);
            return captureFingerPose(s.world, b.arms.Right!.hand).joints;
        };
        const byName = await fingersOf({ mainPose: 'pistol' });
        const expanded = gripPoseByJoint(gripPose('pistol')!);
        const byJoint = await fingersOf({ mainPose: '', mainFingers: JSON.stringify(expanded) });
        expect(Object.keys(byJoint).length).toBeGreaterThan(10);
        for (const [name, r] of Object.entries(byName)) expect(angle(r, byJoint[name]!)).toBeLessThan(2e-3);
        // Twenty degrees more on the middle finger's knuckle: that joint turns by twenty degrees, nothing else on the hand moves.
        const edited = JSON.parse(JSON.stringify(expanded));
        edited.middle.bend[0] += 20;
        const changed = await fingersOf({ mainPose: '', mainFingers: JSON.stringify(edited) });
        for (const [name, r] of Object.entries(byJoint)) {
            const turned = angle(r, changed[name]!);
            if (name === 'mixamorig:RightHandMiddle1') expect(Math.abs(turned - (20 * Math.PI) / 180)).toBeLessThan(2e-3);
            else if (/Thumb/.test(name)) continue; // the thumb reaches for the middle finger, which has moved
            else expect(turned).toBeLessThan(1e-4);
        }
    });

    it('holds a pose said joint by joint the same on either hand, mirrored, lean included', async () => {
        registerGripPose('test-by-joint', { thumb: { opposition: 0 }, index: { curl: 0, bend: [30, 40, 20], fan: 12 }, middle: { curl: 0, bend: [50, 60, 30], fan: 4 }, ring: { curl: 0, bend: [55, 70, 35], fan: 8 }, pinky: { curl: 0, bend: [60, 75, 40], fan: 15 } });
        const s = scene();
        const b = body(s.world);
        s.world.insert(b.root, GripPose, { rightPose: 'test-by-joint', leftPose: 'test-by-joint', blendSeconds: 0 });
        await s.tick(2);
        for (const finger of ['Index', 'Middle', 'Ring', 'Pinky']) {
            const r = worldPose(s.world, descendant(s.world, b.root, `mixamorig:RightHand${finger}4`)).p;
            const l = worldPose(s.world, descendant(s.world, b.root, `mixamorig:LeftHand${finger}4`)).p;
            expect(dist(l, { x: -r.x, y: r.y, z: r.z })).toBeLessThan(1e-4);
        }
    });

    it('leans a finger out from the middle of the hand for a positive lean, the index toward the thumb and the little finger away', async () => {
        const tips = async (fan: number) => {
            registerGripPose(`test-fan-${fan}`, { thumb: { opposition: 0 }, index: { curl: 0, fan }, middle: { curl: 0 }, ring: { curl: 0 }, pinky: { curl: 0, fan } });
            const s = scene();
            const b = body(s.world);
            s.world.insert(b.root, GripPose, { rightPose: `test-fan-${fan}`, blendSeconds: 0 });
            await s.tick(2);
            const at = (f: string) => worldPose(s.world, descendant(s.world, b.root, `mixamorig:RightHand${f}4`)).p;
            return { index: at('Index'), pinky: at('Pinky'), middle: at('Middle') };
        };
        const flat = await tips(0), out = await tips(20);
        expect(dist(out.index, out.pinky)).toBeGreaterThan(dist(flat.index, flat.pinky) + 0.02);
        expect(dist(out.index, out.middle)).toBeGreaterThan(dist(flat.index, flat.middle) + 0.01);
    });

    it('reads fingers from JSON leniently, and refuses text that is not a pose', () => {
        expect(gripPoseFromJson('')).toBeNull();
        expect(gripPoseFromJson('not json')).toBeNull();
        expect(gripPoseFromJson('3')).toBeNull();
        const partial = gripPoseFromJson('{"index":{"bend":[10,20,30]},"thumb":{"opposition":0.5,"to":"index"}}')!;
        expect(partial.index.bend).toEqual([10, 20, 30]);
        expect(partial.middle.curl).toBe(0);
        expect(partial.thumb).toEqual({ opposition: 0.5, to: 'index', gap: 0 });
        expect(gripPoseFromJson('{"index":{"bend":[10,"x",30]}}')!.index.bend).toBeUndefined();
    });

    it('says how far a palm stops short of an anchor out of reach, and nothing within it', async () => {
        const s = scene();
        const b = body(s.world);
        const g = gun(s.world, { x: -0.15, y: 1.25, z: 0.45 });
        holder(s.world, b.root, { held: g.e, placement: GripPlacement.Object, supportWeight: 0 });
        await s.tick(2);
        expect(gripHolderStatus(s.app, b.root)!.short.main).toBe(0);
        s.world.update(g.e, Transform, (t: TransformData) => { t.position = { x: -0.15, y: 1.25, z: 3 }; });
        await s.tick(2);
        const short = gripHolderStatus(s.app, b.root)!.short.main;
        // The arm is 0.57 long from a shoulder at z 0.05; the anchor is about 2.93 ahead of it.
        expect(short).toBeGreaterThan(2.2);
        expect(short).toBeLessThan(2.5);
    });

    it('previews in an editor only with the effects preview on, and gives every bone and the carried object back when it ends', async () => {
        const s = scene();
        setPlayMode(false);
        setEditorMode(true);
        const b = body(s.world);
        const g = gun(s.world, { x: 3, y: 0, z: 0 });
        s.world.update(g.e, GripProfile, (p: { mainPose: string; supportPose: string }) => { p.mainPose = 'fist'; p.supportPose = 'fist'; });
        reachable(s.world, g);
        holder(s.world, b.root, { held: g.e, placement: GripPlacement.Hand });
        const fingers = () => Object.values(captureFingerPose(s.world, b.arms.Left!.hand).joints);
        const before = { arms: rotationsOf(s.world, armJoints(b)), fingers: fingers(), gun: { ...(s.world.get(g.e, Transform) as TransformData).position } };
        await s.tick(5);
        expect(rotationsOf(s.world, armJoints(b))).toEqual(before.arms);
        setFxEditPreview(true);
        await s.tick(30);
        expect(dist((s.world.get(g.e, Transform) as TransformData).position, before.gun)).toBeGreaterThan(1);
        expect(Math.max(...rotationsOf(s.world, armJoints(b)).map((r, i) => angle(r, before.arms[i]!)))).toBeGreaterThan(0.1);
        expect(Math.max(...fingers().map((r, i) => angle(r, before.fingers[i]!)))).toBeGreaterThan(0.5);
        releaseGripHolds(s.app);
        setFxEditPreview(false);
        await s.tick(2);
        rotationsOf(s.world, armJoints(b)).forEach((r, i) => expect(angle(r, before.arms[i]!)).toBeLessThan(1e-5));
        fingers().forEach((r, i) => expect(angle(r, before.fingers[i]!)).toBeLessThan(1e-5));
        expect(dist((s.world.get(g.e, Transform) as TransformData).position, before.gun)).toBeLessThan(1e-6);
    });
});

/** An entity below `root` by name. */
function descendant(world: World, root: Entity, name: string): Entity {
    const stack = [root];
    while (stack.length) {
        const at = stack.pop()!;
        if ((world.tryGet(at, Name) as { value?: string } | null)?.value === name) return at;
        stack.push(...((world.tryGet(at, Children) as { entities?: Entity[] } | null)?.entities ?? []));
    }
    throw new Error(`no ${name}`);
}


/** How far a point is from a line through `on` along `along` (a unit vector). */
function fromLine(p: V, on: V, along: V): number {
    const d = { x: p.x - on.x, y: p.y - on.y, z: p.z - on.z };
    const k = d.x * along.x + d.y * along.y + d.z * along.z;
    return Math.hypot(d.x - along.x * k, d.y - along.y * k, d.z - along.z * k);
}

describe.skipIf(!HAS_WASM)('closing the fingers onto what is held', () => {
    beforeAll(async () => { if (HAS_WASM) core = await loadWasmModule(); });

    const FOUR = ['Index', 'Middle', 'Ring', 'Pinky'] as const;
    /** The index finger's length, and a finger's thickness from its line to its skin: what the fingers stop short of a surface by. */
    const SKIN = (0.04 + 0.025 + 0.02) * 0.08;

    /**
     * A right hand held on a gun by its anchor, a handle running across the palm under the knuckles: a cylinder on the anchor, along its X,
     * `radius` round. Its axis in the world, and the hand's finger bones, come back.
     */
    async function onHandle(radius: number, options: { pose?: string; wrap?: boolean; shape?: number; size?: V; fingers?: string; center?: V } = {}) {
        const s = scene();
        const b = body(s.world);
        const g = gun(s.world, { x: -0.15, y: 1.25, z: 0.45 });
        s.world.update(g.e, GripProfile, (p: GripProfileData) => { p.mainPose = options.pose ?? 'fist'; p.wrap = options.wrap ?? true; p.mainFingers = options.fingers ?? ''; });
        // The palm faces the anchor's +Y: the handle lies that way from it, a little ahead, under where the fingers start.
        const center = options.center ?? { x: 0, y: radius + 0.012, z: 0.05 };
        s.world.insert(g.main, GripSurface, { shape: options.shape ?? GripSurfaceShape.Cylinder, direction: 0, center, radius, height: 0.2, size: options.size ?? { x: 0.2, y: 0.03, z: 0.03 } });
        holder(s.world, b.root, { held: g.e, placement: GripPlacement.Object, supportWeight: 0 });
        await s.tick(4);
        const anchor = worldPose(s.world, g.main);
        const axis = { on: (() => { const v = q.rotate(anchor.r, center); return { x: anchor.p.x + v.x, y: anchor.p.y + v.y, z: anchor.p.z + v.z }; })(), along: q.rotate(anchor.r, { x: 1, y: 0, z: 0 }) };
        const bones = (finger: string): V[] => [1, 2, 3, 4].map((i) => worldPose(s.world, descendant(s.world, b.arms.Right!.hand, `mixamorig:RightHand${finger}${i}`)).p);
        /** The nearest any point of a finger's bones comes to the handle's axis. */
        const nearest = (finger: string): number => {
            const at = bones(finger);
            let best = Infinity;
            for (let k = 0; k < 3; k++) for (let i = 0; i <= 8; i++) {
                const t = i / 8, a = at[k]!, c = at[k + 1]!;
                best = Math.min(best, fromLine({ x: a.x + (c.x - a.x) * t, y: a.y + (c.y - a.y) * t, z: a.z + (c.z - a.z) * t }, axis.on, axis.along));
            }
            return best;
        };
        const bendOf = (finger: string): number => [1, 2, 3].reduce((n, i) => n + angle((s.world.get(descendant(s.world, b.arms.Right!.hand, `mixamorig:RightHand${finger}${i}`), Transform) as TransformData).rotation, I), 0);
        return { s, b, g, axis, bones, nearest, bendOf, status: () => gripPoseStatus(s.app, b.root)!.right };
    }

    it('closes each finger until its bones meet the handle, and no further: on its skin, never inside it', async () => {
        const R = 0.02;
        const h = await onHandle(R);
        expect(h.status().touching.filter((f) => f !== 'thumb').sort()).toEqual(['index', 'middle', 'pinky', 'ring']);
        for (const finger of FOUR) {
            // Within a ten-thousandth of the skin: the bisection's own step, and float32 bones.
            expect(h.nearest(finger)).toBeGreaterThan(R + SKIN - 3e-4);
            expect(h.nearest(finger)).toBeLessThan(R + SKIN + 1e-3);
        }
    });

    it('closes further round a thinner handle, and less round a thicker one', async () => {
        const thin = await onHandle(0.012), thick = await onHandle(0.03);
        for (const finger of FOUR) expect(thin.bendOf(finger)).toBeGreaterThan(thick.bendOf(finger) + 0.1);
    });

    it('closes no further than the pose does, where the pose stops short of the handle', async () => {
        const open = await onHandle(0.02, { pose: 'relaxed' });
        const unwrapped = await onHandle(0.02, { pose: 'relaxed', wrap: false });
        // The relaxed index finger is the least curled: it stops short, and is exactly as the pose has it.
        expect(open.status().touching).not.toContain('index');
        for (const finger of FOUR) {
            if (open.status().touching.includes(finger.toLowerCase())) expect(open.bendOf(finger)).toBeLessThan(unwrapped.bendOf(finger));
            else expect(Math.abs(open.bendOf(finger) - unwrapped.bendOf(finger))).toBeLessThan(1e-4);
        }
    });

    it('goes through the handle with wrap off, as the pose says', async () => {
        const h = await onHandle(0.02, { wrap: false });
        expect(h.status().touching).toEqual([]);
        expect(Math.min(...FOUR.map((f) => h.nearest(f)))).toBeLessThan(0.02);
    });

    it('rests the thumb on the handle rather than inside it', async () => {
        const R = 0.02;
        const h = await onHandle(R);
        const tip = worldPose(h.s.world, descendant(h.s.world, h.b.arms.Right!.hand, 'mixamorig:RightHandThumb4')).p;
        expect(fromLine(tip, h.axis.on, h.axis.along)).toBeGreaterThan(R + SKIN - 3e-4);
        expect(h.nearest('Thumb')).toBeGreaterThan(R + SKIN - 3e-4);
        expect(h.status().touching).toContain('thumb');
    });

    it('closes onto a box and a sphere the same way, on their skin', async () => {
        const box = await onHandle(0.02, { shape: GripSurfaceShape.Box, size: { x: 0.2, y: 0.04, z: 0.04 } });
        expect(box.status().touching.length).toBeGreaterThan(2);
        const ball = await onHandle(0.03, { shape: GripSurfaceShape.Sphere });
        expect(ball.status().touching.length).toBeGreaterThan(0);
    });

    it('holds every joint before the bone that touched: a fingertip meeting the object first stops the whole finger there', () => {
        // Three joints closing to 1 together; the tip's bone (2) touches once the last joint passes 0.5.
        const { bends, touched } = closeFinger([0, 0, 0], [1, 1, 1], (b, from) => (from <= 2 && b[2]! >= 0.5 ? 2 : -1));
        expect(touched).toBe(true);
        for (const b of bends) expect(b).toBeCloseTo(0.5, 2);
        // A knuckle's bone touching holds only the knuckle: the rest go on to the pose.
        const knuckle = closeFinger([0, 0, 0], [1, 1, 1], (b, from) => (from <= 0 && b[0]! >= 0.3 ? 0 : -1));
        expect(knuckle.bends[0]).toBeCloseTo(0.3, 2);
        expect(knuckle.bends[1]).toBe(1);
        expect(knuckle.bends[2]).toBe(1);
    });

    it('fits a finger as it leans: each finger leaning out, closed onto a ball, rests on its skin', async () => {
        const lean = (fan: number) => ({ curl: 1, bend: [90, 100, 70], fan });
        const fingers = JSON.stringify({ thumb: { opposition: 0 }, index: lean(25), middle: lean(25), ring: lean(25), pinky: lean(25) });
        const h = await onHandle(0.03, { shape: GripSurfaceShape.Sphere, fingers, center: { x: 0, y: 0.045, z: 0.06 } });
        const placed = surfacesUnder(h.s.world, h.g.e);
        const touching = h.status().touching.filter((f) => f !== 'thumb');
        expect(touching.length).toBeGreaterThan(1);
        for (const finger of touching) {
            const at = h.bones(finger.charAt(0).toUpperCase() + finger.slice(1));
            let near = Infinity;
            for (let k = 0; k < 3; k++) for (let i = 0; i <= 8; i++) {
                const t = i / 8, a = at[k]!, c = at[k + 1]!;
                near = Math.min(near, surfaceDistance(placed, { x: a.x + (c.x - a.x) * t, y: a.y + (c.y - a.y) * t, z: a.z + (c.z - a.z) * t }));
            }
            expect(near, finger).toBeGreaterThan(SKIN - 3e-4);
            expect(near, finger).toBeLessThan(SKIN + 1e-3);
        }
    });

    it('goes back over fingers something else turned after the hand settled, with no clip component to say so: an editor sampling a clip', async () => {
        const h = await onHandle(0.02);
        const knuckle = descendant(h.s.world, h.b.arms.Right!.hand, 'mixamorig:RightHandIndex1');
        const held = { ...(h.s.world.get(knuckle, Transform) as TransformData).rotation };
        h.s.world.update(knuckle, Transform, (t: TransformData) => { t.rotation = q.normalize({ w: 0.9, x: 0.3, y: 0.2, z: 0.1 }); });
        await h.s.tick(1);
        expect(angle((h.s.world.get(knuckle, Transform) as TransformData).rotation, held)).toBeLessThan(1e-4);
    });

    it('says which joints each hand bends and the axis a positive bend turns each about', async () => {
        const h = await onHandle(0.02);
        const joints = gripHandJoints(h.s.app, h.b.root)!;
        expect(joints.right.map((j) => `${j.finger}${j.joint}`)).toEqual(['index0', 'index1', 'index2', 'middle0', 'middle1', 'middle2', 'ring0', 'ring1', 'ring2', 'pinky0', 'pinky1', 'pinky2']);
        const knuckle = joints.right[0]!;
        expect(knuckle.entity).toBe(descendant(h.s.world, h.b.arms.Right!.hand, 'mixamorig:RightHandIndex1'));
        expect(Math.hypot(knuckle.axis.x, knuckle.axis.y, knuckle.axis.z)).toBeCloseTo(1, 5);
        // The knuckle's bone runs to the next joint; the last joint's to the fingertip.
        expect(dist(knuckle.bone, (h.s.world.get(descendant(h.s.world, h.b.arms.Right!.hand, 'mixamorig:RightHandIndex2'), Transform) as TransformData).position)).toBeLessThan(1e-6);
        expect(dist(joints.right[2]!.bone, (h.s.world.get(descendant(h.s.world, h.b.arms.Right!.hand, 'mixamorig:RightHandIndex4'), Transform) as TransformData).position)).toBeLessThan(1e-6);
    });

    it('draws each surface where the fingers meet it: every point of its lines on it', async () => {
        for (const shape of [GripSurfaceShape.Cylinder, GripSurfaceShape.Capsule, GripSurfaceShape.Sphere, GripSurfaceShape.Box]) {
            const h = await onHandle(0.02, { shape, size: { x: 0.1, y: 0.04, z: 0.03 } });
            const lines = gripSurfaceLines(h.s.world, h.g.e);
            expect(lines.length).toBeGreaterThan(2);
            const placed = surfacesUnder(h.s.world, h.g.e);
            for (const line of lines) for (const p of line) expect(Math.abs(surfaceDistance(placed, p))).toBeLessThan(1e-5);
        }
    });
});