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.

18.2 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect, beforeEach } from 'vitest';
import { World } from '../src/ecs/world';
import { Sprite, type SpriteData } from '../src/ecs/component';
import type { CppRegistry, ESEngineModule } from '../src/wasm';
import type { Entity } from '../src/types';
import {
    SpriteAnimator,
    SpriteAnimationAPI,
    type SpriteAnimatorData,
    type SpriteAnimClip,
} from '../src/animation/SpriteAnimator';
import { parseAnimClipAsset, parseAnimClipData } from '../src/animation/AnimClipLoader';

function createAnimTestWorld(): { world: World; registry: CppRegistry } {
    const spriteStore = new Map<Entity, Record<string, unknown>>();
    let nextEntity = 1;

    const registry: Record<string, Function | undefined> = {
        create: () => nextEntity++ as Entity,
        destroy: () => {},
        isValid: (e: Entity) => true,
        delete: () => {},
        removeParent: () => {},
        addSprite(entity: Entity, data: Record<string, unknown>) {
            spriteStore.set(entity, { ...data });
        },
        getSprite(entity: Entity) {
            return spriteStore.get(entity);
        },
        hasSprite(entity: Entity) {
            return spriteStore.has(entity);
        },
        removeSprite(entity: Entity) {
            spriteStore.delete(entity);
        },
    };

    const module = {
        registry_getGeneration: () => 0,
    } as unknown as ESEngineModule;

    const cppRegistry = registry as unknown as CppRegistry;
    const world = new World();
    world.connectCpp(cppRegistry, module);
    return { world, registry: cppRegistry };
}

describe('SpriteAnimator', () => {
    let world: World;
    let anim: SpriteAnimationAPI;

    beforeEach(() => {
        const ctx = createAnimTestWorld();
        world = ctx.world;
        anim = new SpriteAnimationAPI();
    });

    // =========================================================================
    // Component Definition
    // =========================================================================

    describe('component definition', () => {
        it('should be a named component', () => {
            expect(SpriteAnimator._name).toBe('SpriteAnimator');
        });

        it('should have correct defaults', () => {
            expect(SpriteAnimator._default).toEqual({
                clip: '',
                speed: 1.0,
                playing: true,
                loop: true,
                enabled: true,
                currentFrame: 0,
                frameTimer: 0,
                finished: false,
            });
        });

        it('should be a user component (not builtin)', () => {
            expect(SpriteAnimator._builtin).toBe(false);
        });
    });

    // =========================================================================
    // Clip Registry
    // =========================================================================

    describe('clip registry', () => {
        const testClip: SpriteAnimClip = {
            name: 'walk',
            frames: [
                { texture: 1 },
                { texture: 2 },
                { texture: 3 },
            ],
            fps: 10,
            loop: true,
        };

        it('should register and retrieve a clip', () => {
            anim.registerClip(testClip);
            const retrieved = anim.getClip('walk');
            expect(retrieved).toEqual(testClip);
        });

        it('should return undefined for unregistered clip', () => {
            expect(anim.getClip('nonexistent')).toBeUndefined();
        });

        it('should unregister a clip', () => {
            anim.registerClip(testClip);
            anim.unregisterClip('walk');
            expect(anim.getClip('walk')).toBeUndefined();
        });

        it('should clear all clips', () => {
            anim.registerClip(testClip);
            anim.registerClip({ ...testClip, name: 'run' });
            anim.clearClips();
            expect(anim.getClip('walk')).toBeUndefined();
            expect(anim.getClip('run')).toBeUndefined();
        });
    });

    // =========================================================================
    // System Update
    // =========================================================================

    describe('system update', () => {
        const walkClip: SpriteAnimClip = {
            name: 'walk',
            frames: [
                { texture: 10 },
                { texture: 20 },
                { texture: 30 },
            ],
            fps: 10,
            loop: true,
        };

        beforeEach(() => {
            anim.registerClip(walkClip);
        });

        it('should apply first frame texture on initial tick', () => {
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 0 });
            world.insert(entity, SpriteAnimator, { clip: 'walk' });

            anim.update(world, 0.001);

            const sprite = world.get(entity, Sprite) as SpriteData;
            expect(sprite.texture).toBe(10);
        });

        it('should advance frame after enough time', () => {
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 10 });
            world.insert(entity, SpriteAnimator, { clip: 'walk' });

            // fps=10, frameDuration=0.1s, dt=0.1 should advance one frame
            anim.update(world, 0.1);

            const sprite = world.get(entity, Sprite) as SpriteData;
            expect(sprite.texture).toBe(20);
        });

        it('should not advance frame before duration', () => {
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 10 });
            world.insert(entity, SpriteAnimator, { clip: 'walk' });

            anim.update(world, 0.05);

            const sprite = world.get(entity, Sprite) as SpriteData;
            expect(sprite.texture).toBe(10);
        });

        it('advances MULTIPLE frames when one dt spans several (no slow-motion)', () => {
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 10 });
            world.insert(entity, SpriteAnimator, { clip: 'walk' });

            // fps=10 → 0.1s/frame; 0.25s spans 2.5 frames → reach frame 2 (30), not 1 (20).
            anim.update(world, 0.25);

            expect((world.get(entity, Sprite) as SpriteData).texture).toBe(30);
        });

        it('scales an EXPLICIT frame duration by animator.speed', () => {
            anim.registerClip({
                name: 'timed', fps: 10, loop: true,
                frames: [{ texture: 1, duration: 0.1 }, { texture: 2, duration: 0.1 }],
            });
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 1 });
            world.insert(entity, SpriteAnimator, { clip: 'timed', speed: 2 });

            // speed 2 halves the 0.1s frame → 0.06s advances one frame (speed was
            // previously ignored for explicit durations).
            anim.update(world, 0.06);

            expect((world.get(entity, Sprite) as SpriteData).texture).toBe(2);
        });

        it('should loop back to first frame', () => {
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 10 });
            world.insert(entity, SpriteAnimator, { clip: 'walk' });

            // Advance through all 3 frames (3 * 0.1 = 0.3s)
            anim.update(world, 0.1);
            anim.update(world, 0.1);
            anim.update(world, 0.1);

            const sprite = world.get(entity, Sprite) as SpriteData;
            expect(sprite.texture).toBe(10); // looped back to frame 0
        });

        it('should stop at last frame when loop is false', () => {
            const noLoopClip: SpriteAnimClip = {
                name: 'explode',
                frames: [{ texture: 100 }, { texture: 200 }],
                fps: 10,
                loop: false,
            };
            anim.registerClip(noLoopClip);

            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 100 });
            world.insert(entity, SpriteAnimator, { clip: 'explode', loop: false });

            anim.update(world, 0.1); // frame 0 -> 1
            anim.update(world, 0.1); // frame 1 -> would be 2, clamp to 1

            const sprite = world.get(entity, Sprite) as SpriteData;
            expect(sprite.texture).toBe(200);

            const animator = world.get(entity, SpriteAnimator) as SpriteAnimatorData;
            expect(animator.playing).toBe(false);
        });

        it('should skip disabled entities', () => {
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 10 });
            world.insert(entity, SpriteAnimator, { clip: 'walk', enabled: false });

            anim.update(world, 0.1);

            const sprite = world.get(entity, Sprite) as SpriteData;
            expect(sprite.texture).toBe(10);
        });

        it('should skip paused entities', () => {
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 10 });
            world.insert(entity, SpriteAnimator, { clip: 'walk', playing: false });

            anim.update(world, 0.1);

            const sprite = world.get(entity, Sprite) as SpriteData;
            expect(sprite.texture).toBe(10);
        });

        it('should skip entities with empty clip name', () => {
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 10 });
            world.insert(entity, SpriteAnimator, { clip: '' });

            anim.update(world, 0.1);

            const sprite = world.get(entity, Sprite) as SpriteData;
            expect(sprite.texture).toBe(10);
        });

        it('should skip entities with unregistered clip', () => {
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 10 });
            world.insert(entity, SpriteAnimator, { clip: 'missing_clip' });

            anim.update(world, 0.1);

            const sprite = world.get(entity, Sprite) as SpriteData;
            expect(sprite.texture).toBe(10);
        });

        it('should respect speed multiplier', () => {
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 10 });
            world.insert(entity, SpriteAnimator, { clip: 'walk', speed: 2.0 });

            // speed=2, fps=10, frameDuration=0.05s
            anim.update(world, 0.05);

            const sprite = world.get(entity, Sprite) as SpriteData;
            expect(sprite.texture).toBe(20);
        });

        it('should handle multiple entities independently', () => {
            const e1 = world.spawn();
            world.insert(e1, Sprite, { texture: 10 });
            world.insert(e1, SpriteAnimator, { clip: 'walk' });

            const e2 = world.spawn();
            world.insert(e2, Sprite, { texture: 10 });
            world.insert(e2, SpriteAnimator, { clip: 'walk', speed: 2.0 });

            // e1: frameDuration=0.1, e2: frameDuration=0.05
            anim.update(world, 0.05);

            const s1 = world.get(e1, Sprite) as SpriteData;
            const s2 = world.get(e2, Sprite) as SpriteData;
            expect(s1.texture).toBe(10); // not advanced yet
            expect(s2.texture).toBe(20); // advanced
        });
    });

    // =========================================================================
    // Per-frame anchors
    // =========================================================================

    describe('per-frame anchors', () => {
        it('applies the frame anchor to Sprite.pivot as frames advance', () => {
            anim.registerClip({
                name: 'anchored', fps: 10, loop: true,
                frames: [
                    { texture: 1, pivot: { x: 0.5, y: 0 } },
                    { texture: 2, pivot: { x: 0.25, y: 0.1 } },
                ],
            });
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 0 });
            world.insert(entity, SpriteAnimator, { clip: 'anchored' });

            anim.update(world, 0.001);
            expect((world.get(entity, Sprite) as SpriteData).pivot).toEqual({ x: 0.5, y: 0 });

            anim.update(world, 0.1);
            expect((world.get(entity, Sprite) as SpriteData).pivot).toEqual({ x: 0.25, y: 0.1 });
        });

        it('leaves the entity pivot alone for a clip that authors no anchors', () => {
            anim.registerClip({
                name: 'plain', fps: 10, loop: true,
                frames: [{ texture: 10 }, { texture: 20 }],
            });
            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 0, pivot: { x: 0.5, y: 0 } });
            world.insert(entity, SpriteAnimator, { clip: 'plain' });

            anim.update(world, 0.001);
            anim.update(world, 0.1);

            // No frame carries a pivot: the entity's own anchor stands.
            expect((world.get(entity, Sprite) as SpriteData).pivot).toEqual({ x: 0.5, y: 0 });
        });

        it('carries an anchor from .esanim TEXT all the way onto the Sprite', () => {
            // The whole production path in one go: file text → tolerant parse → runtime
            // bake → animator apply, which is what a shipped clip actually travels.
            const text = JSON.stringify({
                version: '1.4',
                type: 'animation-clip',
                fps: 10,
                loop: true,
                pivot: { x: 0.5, y: 0 },
                frames: [
                    { texture: 'walk_0.png' },
                    { texture: 'walk_1.png', pivot: { x: 0.25, y: 0.75 } },
                ],
            });
            const data = parseAnimClipAsset(JSON.parse(text));
            anim.registerClip(parseAnimClipData('walk.esanim', data, new Map([
                ['walk_0.png', 11], ['walk_1.png', 22],
            ])));

            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 0, pivot: { x: 0.5, y: 0.5 } });
            world.insert(entity, SpriteAnimator, { clip: 'walk.esanim' });

            anim.update(world, 0.001);
            let sprite = world.get(entity, Sprite) as SpriteData;
            expect(sprite.texture).toBe(11);
            expect(sprite.pivot).toEqual({ x: 0.5, y: 0 }); // clip-wide anchor

            anim.update(world, 0.1);
            sprite = world.get(entity, Sprite) as SpriteData;
            expect(sprite.texture).toBe(22);
            expect(sprite.pivot).toEqual({ x: 0.25, y: 0.75 }); // frame override
        });
    });

    // =========================================================================
    // Per-frame size and offset
    // =========================================================================

    describe('per-frame size', () => {
        it('draws each frame at its own texture size', () => {
            const data = parseAnimClipAsset({
                version: '1.5', type: 'animation-clip', fps: 10, loop: true,
                frameSizing: 'frame',
                frames: [{ texture: 'wide.png' }, { texture: 'tall.png' }],
            });
            anim.registerClip(parseAnimClipData('seq.esanim', data,
                new Map([['wide.png', 11], ['tall.png', 22]]),
                new Map([['wide.png', { x: 96, y: 64 }], ['tall.png', { x: 48, y: 80 }]])));

            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 0, size: { x: 100, y: 100 } });
            world.insert(entity, SpriteAnimator, { clip: 'seq.esanim' });

            anim.update(world, 0.001);
            expect((world.get(entity, Sprite) as SpriteData).size).toEqual({ x: 96, y: 64 });

            anim.update(world, 0.1);
            expect((world.get(entity, Sprite) as SpriteData).size).toEqual({ x: 48, y: 80 });
        });

        it('leaves the entity size alone for a clip that does not own size', () => {
            const data = parseAnimClipAsset({
                version: '1.4', type: 'animation-clip', fps: 10, loop: true,
                frames: [{ texture: 'a.png' }, { texture: 'b.png' }],
            });
            anim.registerClip(parseAnimClipData('plain.esanim', data,
                new Map([['a.png', 11], ['b.png', 22]]),
                new Map([['a.png', { x: 96, y: 64 }], ['b.png', { x: 48, y: 80 }]])));

            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 0, size: { x: 100, y: 100 } });
            world.insert(entity, SpriteAnimator, { clip: 'plain.esanim' });

            anim.update(world, 0.001);
            anim.update(world, 0.1);

            expect((world.get(entity, Sprite) as SpriteData).size).toEqual({ x: 100, y: 100 });
        });

        it('shifts differently-sized frames by the SAME world distance', () => {
            // The reason offsets exist. A normalized pivot cannot do this: the same
            // fraction on a 96-wide and a 48-wide frame are different shifts.
            const data = parseAnimClipAsset({
                version: '1.5', type: 'animation-clip', fps: 10, loop: true,
                frames: [
                    { texture: 'big.png', offset: { x: 12, y: -5 } },
                    { texture: 'small.png', offset: { x: 12, y: -5 } },
                ],
            });
            anim.registerClip(parseAnimClipData('shift.esanim', data,
                new Map([['big.png', 11], ['small.png', 22]]),
                new Map([['big.png', { x: 96, y: 64 }], ['small.png', { x: 48, y: 32 }]])));

            const entity = world.spawn();
            world.insert(entity, Sprite, { texture: 0 });
            world.insert(entity, SpriteAnimator, { clip: 'shift.esanim' });

            // How far the artwork sits from the anchor, in world units: the centre of
            // the frame is (0.5 - pivot) of its size away from it.
            const shiftOf = (s: SpriteData) => ({
                x: (0.5 - s.pivot.x) * s.size.x,
                y: (0.5 - s.pivot.y) * s.size.y,
            });

            anim.update(world, 0.001);
            const big = shiftOf(world.get(entity, Sprite) as SpriteData);
            expect(big.x).toBeCloseTo(12, 10);
            expect(big.y).toBeCloseTo(-5, 10);

            anim.update(world, 0.1);
            const small = shiftOf(world.get(entity, Sprite) as SpriteData);
            expect(small.x).toBeCloseTo(12, 10);
            expect(small.y).toBeCloseTo(-5, 10);
        });
    });
});