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.

8.9 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    spine-atlas-page-resolve.test.ts
 * @brief   Regression: a spine atlas names its pages by AUTHORED filename
 *          (`spineboy.png`), but a cook may re-encode the staged file (.ktx2)
 *          or content-address it. The page path must resolve through
 *          `source.resolveRef` like every other fetch, and a KTX2 page must
 *          transcode through the realm's basis provider instead of the image
 *          decoder (which cannot decode KTX2 on any platform).
 */
import { describe, it, expect, vi } from 'vitest';

// The page-form decision (KTX2 through the realm's decoder, else the image path)
// lives in runtimeAssets and is the thing under test, so only the upload below it
// is stood in for — a ResourceManager that takes bytes, as a native host's does.
const { rm } = vi.hoisted(() => ({
    rm: {
        registerTextureWithPath: vi.fn(),
        getTextureGLId: vi.fn(() => 7),
        createTextureFromBytes: vi.fn(() => 11),
    },
}));
vi.mock('../src/wasm/resourceManager', () => ({
    requireResourceManager: () => rm,
    provideTextureContent: () => {},
}));

import { loadSpineAssets } from '../src/spine/loadSpineScene';
import { SpineAssetLoader } from '../src/asset/loaders/SpineAssetLoader';
import { Catalog } from '../src/asset/Catalog';
import type { RuntimeAssetSource } from '../src/runtime/runtimeAssets';
import type { BasisTranscoder } from '../src/asset/compressed';

const ATLAS = 'spineboy.png\nsize: 4,4\nformat: RGBA8888\n';

function makeSource(resolved: Record<string, string>): RuntimeAssetSource & {
    decodePixels: ReturnType<typeof vi.fn>;
    fetchedBinaries: string[];
} {
    const fetchedBinaries: string[] = [];
    return {
        backend: {
            fetchText: vi.fn(async () => ATLAS),
            fetchBinary: vi.fn(async (p: string) => {
                fetchedBinaries.push(p);
                return new Uint8Array([1, 2, 3]).buffer;
            }),
        } as never,
        decodePixels: vi.fn(async () => ({ width: 4, height: 4, pixels: new Uint8Array(64) })),
        resolveRef: (r: string) => resolved[r] ?? r,
        fetchedBinaries,
    };
}

const PAIR = [{ skeleton: 'assets/spine/boy.skel', atlas: 'assets/spine/boy.atlas' }];

describe('loadSpineAssets resolves atlas page paths through the manifest', () => {
    it('transcodes a KTX2-staged page via the basis provider, keyed by logical path', async () => {
        const source = makeSource({ 'assets/spine/spineboy.png': 'assets/spine/spineboy.ktx2' });
        const transcoder: BasisTranscoder = {
            transcode: vi.fn(() => null),
            transcodeToRgba: vi.fn(() => ({ width: 2, height: 2, data: new Uint8Array(16) })),
        };
        const info = await loadSpineAssets({} as never, source, null, PAIR, async () => transcoder);

        expect(source.decodePixels).not.toHaveBeenCalled();
        expect(source.fetchedBinaries).toContain('assets/spine/spineboy.ktx2');
        expect(transcoder.transcodeToRgba).toHaveBeenCalledTimes(1);
        // Registered under the LOGICAL path — the atlas's stable identity.
        expect(rm.registerTextureWithPath).toHaveBeenCalledWith(11, 'assets/spine/spineboy.png');
        const tex = info.get('assets/spine/boy.skel:assets/spine/boy.atlas')!.era.value.textures.get('spineboy.png');
        expect(tex).toEqual({ glId: 7, w: 2, h: 2 });
    });

    it('recognizes the WeChat .ktx2.bin staging spelling as KTX2', async () => {
        const source = makeSource({ 'assets/spine/spineboy.png': 'assets/spine/spineboy.ktx2.bin' });
        const transcoder: BasisTranscoder = {
            transcode: vi.fn(() => null),
            transcodeToRgba: vi.fn(() => ({ width: 2, height: 2, data: new Uint8Array(16) })),
        };
        await loadSpineAssets({} as never, source, null, PAIR, async () => transcoder);
        expect(source.decodePixels).not.toHaveBeenCalled();
        expect(transcoder.transcodeToRgba).toHaveBeenCalledTimes(1);
    });

    it('decodes a content-addressed page from its STAGED path', async () => {
        const source = makeSource({ 'assets/spine/spineboy.png': 'assets/1234abcd.png' });
        await loadSpineAssets({} as never, source, null, PAIR);
        expect(source.decodePixels).toHaveBeenCalledWith('assets/1234abcd.png', false);
    });

    it('derives the page dir from a @uuid atlas ref resolved to its PATH (playable)', async () => {
        // The playable resolveRef expands @uuid → logical source path; the page
        // path must come from THAT resolved dir, not the bare @uuid (which gave an
        // empty dir → "/spineboy.png" → ERR_FILE_NOT_FOUND).
        const source = makeSource({
            '@uuid:skel': 'assets/spine/boy.skel',
            '@uuid:atlas': 'assets/spine/boy.atlas',
        });
        await loadSpineAssets({} as never, source, null, [{ skeleton: '@uuid:skel', atlas: '@uuid:atlas' }]);
        expect(source.decodePixels).toHaveBeenCalledWith('assets/spine/spineboy.png', false);
    });

    it('a dirless atlas path yields the bare page name, never a leading slash', async () => {
        const source = makeSource({});
        await loadSpineAssets({} as never, source, null, [{ skeleton: 'boy.skel', atlas: 'boy.atlas' }]);
        expect(source.decodePixels).toHaveBeenCalledWith('spineboy.png', false);
    });

    // A device has no wasm transcoder and never will; its host decodes KTX2 in C++.
    // Asking for the transcoder there is what left every Spine atlas unloadable.
    it('takes a KTX2 page from the ResourceManager when it can decode one', async () => {
        const source = makeSource({ 'assets/spine/spineboy.png': 'assets/spine/spineboy.ktx2' });
        const createTextureFromKTX2 = vi.fn(() => ({ handle: 21, width: 8, height: 8 }));
        Object.assign(rm, { createTextureFromKTX2 });
        try {
            const info = await loadSpineAssets({} as never, source, null, PAIR);

            expect(createTextureFromKTX2).toHaveBeenCalledTimes(1);
            expect(source.decodePixels).not.toHaveBeenCalled();
            expect(rm.registerTextureWithPath).toHaveBeenCalledWith(21, 'assets/spine/spineboy.png');
            const tex = info.get('assets/spine/boy.skel:assets/spine/boy.atlas')!.era.value.textures.get('spineboy.png');
            expect(tex).toEqual({ glId: 7, w: 8, h: 8 });
        } finally {
            delete (rm as { createTextureFromKTX2?: unknown }).createTextureFromKTX2;
        }
    });

    it('a KTX2 page in a realm without basis warns and skips, not throws', async () => {
        const source = makeSource({ 'assets/spine/spineboy.png': 'assets/spine/spineboy.ktx2' });
        const info = await loadSpineAssets({} as never, source, null, PAIR, async () => null);
        expect(info.get('assets/spine/boy.skel:assets/spine/boy.atlas')!.era.value.textures.size).toBe(0);
    });
});

/**
 * The SAME question of the OTHER door. A registry acquisition goes through
 * SpineAssetLoader, which resolved page siblings against the STAGED directory —
 * so every spine in a content-addressed build drew nothing.
 */
describe('SpineAssetLoader page paths', () => {
    /** A pack as staging leaves it: every asset a hash under one flat directory,
     *  addressable by the path it was authored at. */
    function stagedCatalog() {
        return Catalog.fromJson({
            version: 1,
            entries: {
                'assets/spine/boy.atlas': { type: 'spine', buildPath: 'assets/079064052ce23797.atlas' },
                'assets/spine/boy.skel': { type: 'spine', buildPath: 'assets/2f68d725077a3ab0.skel' },
                'assets/spine/spineboy.png': { type: 'texture', buildPath: 'assets/97fac9903b799107.png' },
            },
        });
    }

    function ctxOver(catalog: Catalog, acquired: string[]) {
        return {
            catalog,
            loadText: async () => ATLAS,
            loadBinary: async () => new Uint8Array([1, 2, 3]).buffer,
            acquireTexture: async (path: string) => {
                acquired.push(path);
                return { value: { handle: 5, width: 8, height: 8 } };
            },
        } as never;
    }

    it('names a page where the atlas was AUTHORED, not where staging put it', async () => {
        const acquired: string[] = [];
        await new SpineAssetLoader().prepare(
            'assets/2f68d725077a3ab0.skel', 'assets/079064052ce23797.atlas',
            ctxOver(stagedCatalog(), acquired),
        );
        expect(acquired).toEqual(['assets/spine/spineboy.png']);
    });

    it('falls back to the ref itself when nothing staged it', async () => {
        // Editor and dev realms hand over authored paths and carry no catalog.
        const acquired: string[] = [];
        await new SpineAssetLoader().prepare(
            'assets/spine/boy.skel', 'assets/spine/boy.atlas',
            ctxOver(Catalog.empty(), acquired),
        );
        expect(acquired).toEqual(['assets/spine/spineboy.png']);
    });
});