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.

3.6 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    scenePlugin.ts
 * @brief   Plugin that provides scene management capabilities
 */

import type { App, Plugin } from '../app/app';
import { SceneManager, SceneManagerState } from './sceneManager';
import { SceneStreaming, SceneStreamingController } from './sceneStreaming';
import { worldResidencyPlugin } from '../residency/residencyPlugin';
import { defineSystem, Schedule, GetWorld } from '../ecs/system';
import { Res, ResMut, Time } from '../ecs/resource';
import { Transform, type TransformData } from '../ecs/component';
import { playModeOnly } from '../ecs/env';
import type { SystemDef } from '../ecs/system';
import type { World } from '../ecs/world';
import { log } from '../util/logger';
import { ensureSceneAiRegistrations } from './ai-builtins';

const sceneTransitionSystem = defineSystem(
    [ResMut(SceneManager), Res(Time)],
    (scenesRes, time) => {
        const mgr = scenesRes.get();
        mgr.updateTransition(time.delta);
    },
    { name: 'SceneTransitionSystem' }
);

// Drives proximity streaming: pulls the focus from a follow-entity's Transform (if
// one is set), then reconciles resident cells. A no-op until cells are registered.
// Exported for the criterion that holds the follow to all three axes — the plugin
// is the only place that reads a Transform into a focus.
export const sceneStreamingSystem = defineSystem(
    [Res(SceneStreaming), GetWorld()],
    (streaming: SceneStreamingController, world: World) => {
        const focus = streaming.getFocusEntity();
        if (focus != null && world.valid(focus) && world.has(focus, Transform)) {
            const t = world.get(focus, Transform) as TransformData;
            streaming.setFocus(t.position.x, t.position.y, t.position.z);
        }
        streaming.update();
    },
    // The World is here to read one entity's Transform — the focus the streaming
    // controller follows, which is chosen at runtime rather than queried.
    { name: 'SceneStreamingSystem', touches: { reads: ['Transform'] } }
);

export const sceneManagerPlugin: Plugin = {
    name: 'sceneManager',
    profileDomain: 'scene',
    cleanup(app: App): void {
        if (app.hasResource(SceneManager)) app.getResource(SceneManager).reset();
    },
    build(app: App): void {
        ensureSceneAiRegistrations();
        const state = new SceneManagerState(app);
        app.insertResource(SceneManager, state);
        app.insertResource(SceneStreaming, new SceneStreamingController(state));
        // Residency rides with scenes rather than being wired at each of the three
        // app assemblies: a cell IS an additive scene, so an assembly that can load
        // one can stream one, and a fourth place to remember is a place to forget.
        app.addPlugin(worldResidencyPlugin);

        const initSystem: SystemDef = {
            _id: Symbol('SceneInitSystem'),
            _name: 'SceneInitSystem',
            _params: [],
            _fn: () => {
                const manager = app.getResource(SceneManager);
                const initial = manager.getInitial();
                if (initial) {
                    manager.load(initial).catch(err => {
                        log.error('scene', 'Failed to load initial scene', err);
                    });
                }
            },
        };

        app.addSystemToSchedule(Schedule.Startup, initSystem);
        app.addSystemToSchedule(Schedule.Last, sceneTransitionSystem);
        app.addSystemToSchedule(Schedule.Update, sceneStreamingSystem, { runIf: playModeOnly });
    },
};