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.

9.4 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';

vi.mock('../src/runtime/runtimeLoader', () => ({
    initRuntime: vi.fn().mockResolvedValue(undefined),
}));

vi.mock('../src/asset/AssetPlugin', () => ({
    Assets: Symbol('Assets'),
}));

import { initPlayableRuntime } from '../src/runtime/playableRuntime';
import type { PlayableRuntimeConfig } from '../src/runtime/playableRuntime';
import { initRuntime } from '../src/runtime/runtimeLoader';
import { Assets } from '../src/asset/AssetPlugin';
import { App } from '../src/app/app';
import { Input, InputState } from '../src/input/input';
import type { PlayableAdBridge } from '../src/runtime/playableCta';

function createMockConfig(overrides?: Partial<PlayableRuntimeConfig>): PlayableRuntimeConfig {
    const canvas = { width: 320, height: 480 } as HTMLCanvasElement;
    const mockApp = {
        getResource: vi.fn().mockReturnValue({
            registerEmbeddedAssets: vi.fn(),
            setEmbeddedOnly: vi.fn(),
            setAssetResolver: vi.fn(),   // Audio
            setRefResolver: vi.fn(),     // VideoPlayer
        }),
        hasResource: vi.fn().mockReturnValue(true),
        run: vi.fn(),
    } as any;

    return {
        app: mockApp,
        module: {} as any,
        canvas,
        assets: {},
        scenes: [
            { name: 'main', data: { version: '1', name: 'main', entities: [] } as any },
        ],
        firstScene: 'main',
        ...overrides,
    };
}

describe('initPlayableRuntime', () => {
    beforeEach(() => {
        vi.clearAllMocks();
        delete (globalThis as Record<string, unknown>).__ESTELLA_PLAYABLE__;
    });
    afterEach(() => { delete (globalThis as Record<string, unknown>).__ESTELLA_PLAYABLE__; vi.restoreAllMocks(); });

    it('announces ready after resources load and preserves game pause through host visibility', async () => {
        const app = App.new(), state = new InputState(), order: string[] = [];
        app.insertResource(Input, state); state.keysDown.add('KeyD');
        state.setVirtualSource({}, 'move', 1, 0); state.setVirtual('manual', 1);
        let active!: (value: boolean) => void;
        const release = vi.fn();
        const bridge: PlayableAdBridge = {
            ready: () => { order.push('ready'); },
            onActive: listener => { active = listener; listener(false); return release; },
        };
        (globalThis as Record<string, unknown>).__ESTELLA_PLAYABLE__ = bridge;
        vi.mocked(initRuntime).mockImplementationOnce(async () => { order.push('loaded'); });
        vi.spyOn(app, 'run').mockImplementation(async () => { order.push('run'); });
        await initPlayableRuntime(createMockConfig({ app }));
        expect(order).toEqual(['loaded', 'run', 'ready']);
        expect(app.isPaused()).toBe(true); expect(state.keysDown.size).toBe(0);
        expect(state.getVirtual('move').x).toBe(0); expect(state.getVirtual('manual').x).toBe(1);
        app.setPaused(true); active(true); expect(app.isPaused()).toBe(true);
        app.setPaused(false); active(false); expect(app.isPaused()).toBe(true);
        state.keysDown.add('Space'); active(true); expect(app.isPaused()).toBe(false);
        expect(state.keysDown.size).toBe(0);
        app.quit(); expect(release).toHaveBeenCalledTimes(1);
    });

    it('draws out of sight until the shaders have compiled, when asked to', async () => {
        let compiling = 2;
        const seen: string[] = [];
        const canvas = { width: 320, height: 480, style: { visibility: '' } } as unknown as HTMLCanvasElement;
        const config = createMockConfig({ canvas, prewarmShaders: { timeoutMs: 5000 } });
        (config.app as any).wasmModule = { renderer_getPendingShaders: () => compiling };
        (config.app as any).stepFrames = vi.fn(async () => { seen.push(`frame:${canvas.style.visibility}`); if (compiling > 0) --compiling; });
        (config.app as any).run = vi.fn(async () => { seen.push(`run:${canvas.style.visibility}`); });
        await initPlayableRuntime(config);
        expect(seen.filter((s) => s.startsWith('frame')).every((s) => s === 'frame:hidden')).toBe(true);
        expect(seen.length).toBeGreaterThan(3);
        expect(seen.at(-1)).toBe('run:');

        // A page's start screen comes down between the two: told once everything is warmed, before the loop starts, and shown how
        // the warm-up is going. One that throws must not leave the game unstarted.
        compiling = 2; seen.length = 0;
        const progress: number[] = [];
        await initPlayableRuntime({ ...config, prewarmShaders: { timeoutMs: 5000, onProgress: (n) => progress.push(n) },
            onBeforeRun: () => { seen.push('before-run'); throw new Error('a page that fails'); } });
        expect(progress[0]).toBeGreaterThan(0);
        expect(progress.at(-1)).toBe(0);
        expect(seen.slice(-2)).toEqual(['before-run', 'run:']);

        // Not asked: no frame is drawn before the loop starts.
        const plain = createMockConfig();
        (plain.app as any).stepFrames = vi.fn();
        await initPlayableRuntime(plain);
        expect((plain.app as any).stepFrames).not.toHaveBeenCalled();
    });

    it('passes scenes array and firstScene to initRuntime', async () => {
        const scenes = [
            { name: 'level1', data: { version: '1', name: 'level1', entities: [] } as any },
            { name: 'level2', data: { version: '1', name: 'level2', entities: [] } as any },
        ];
        const config = createMockConfig({ scenes, firstScene: 'level1' });

        await initPlayableRuntime(config);

        expect(initRuntime).toHaveBeenCalledWith(
            expect.objectContaining({
                scenes,
                firstScene: 'level1',
            }),
        );
    });

    it('PlayableRuntimeConfig requires scenes and firstScene fields', async () => {
        const config = createMockConfig();

        await initPlayableRuntime(config);

        const call = vi.mocked(initRuntime).mock.calls[0][0];
        expect(call.scenes).toEqual(config.scenes);
        expect(call.firstScene).toBe('main');
    });

    it('calls app.run() after initRuntime', async () => {
        const config = createMockConfig();

        await initPlayableRuntime(config);

        expect(config.app.run).toHaveBeenCalled();
    });

    // Path-style refs resolve via in-memory aliases onto the embedded map: the
    // alias keys share the data-URL strings (no duplication), and every channel
    // (fetch backend, image decode, audio) reads the same map.
    it('aliases assetPathMap logical paths onto the embedded assets', async () => {
        const config = createMockConfig({
            assets: { '@uuid:aaaa': 'data:text/plain;base64,QQ==' },
            assetPathMap: { 'assets/m.esmaterial': '@uuid:aaaa', 'assets/missing.png': '@uuid:zzzz' },
        });

        await initPlayableRuntime(config);

        const call = vi.mocked(initRuntime).mock.calls[0][0];
        const backend = call.source.backend as { resolveUrl(p: string): string };
        expect(backend.resolveUrl('assets/m.esmaterial')).toBe('data:text/plain;base64,QQ==');
        expect(backend.resolveUrl('/assets/m.esmaterial')).toBe('data:text/plain;base64,QQ==');
        // The original key still resolves; unknown targets alias nothing.
        expect(backend.resolveUrl('@uuid:aaaa')).toBe('data:text/plain;base64,QQ==');
    });

    // resolveRef must yield a logical PATH for an embedded @uuid key, not the bare
    // key: consumers derive sibling paths from a resolved ref (a Spine atlas names
    // its texture pages by filename, resolved against the atlas's directory).
    // Regression: an identity resolveRef left the atlas dir empty → "/spineboy.png"
    // → ERR_FILE_NOT_FOUND on a single-file playable.
    it('resolveRef expands an embedded @uuid to its logical source path', async () => {
        const config = createMockConfig({
            assets: { '@uuid:atlas': 'data:application/octet-stream;base64,QQ==' },
            assetPathMap: { 'assets/spine/boy.atlas': '@uuid:atlas' },
        });

        await initPlayableRuntime(config);

        const call = vi.mocked(initRuntime).mock.calls[0][0];
        const resolveRef = call.source.resolveRef as (r: string) => string;
        expect(resolveRef('@uuid:atlas')).toBe('assets/spine/boy.atlas');
        // A ref with no known path (or already a path) passes through unchanged.
        expect(resolveRef('assets/spine/boy.png')).toBe('assets/spine/boy.png');
        expect(resolveRef('@uuid:unknown')).toBe('@uuid:unknown');
    });

    // A single-file playable makes NO external requests — its `file://` page is a
    // null origin whose sibling fetches are CORS-blocked. Video is the newest
    // asset channel, so it must resolve through the SAME embedded map as every
    // other subsystem: the clip ref maps to its inlined data URL.
    it('wires the video ref resolver to the embedded data-URL map', async () => {
        const config = createMockConfig({
            assets: { 'assets/video/clip.mp4': 'data:video/mp4;base64,AAAA' },
        });

        await initPlayableRuntime(config);

        const resolver = (config.app.getResource() as { setRefResolver: ReturnType<typeof vi.fn> })
            .setRefResolver.mock.calls[0][0] as (ref: string) => string;
        expect(resolver('assets/video/clip.mp4')).toBe('data:video/mp4;base64,AAAA');
        expect(resolver('assets/nope.mp4')).toBe('assets/nope.mp4'); // passthrough, no external fetch key
    });
});