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.

refactor(sdk): per-App camera query API + scratch pool (F3 B1)

esengine5b23cabe1947
diff --git a/sdk/src/camera/Camera.ts b/sdk/src/camera/Camera.ts
index f5a1f93b9..f676a6cdd 100644
--- a/sdk/src/camera/Camera.ts
+++ b/sdk/src/camera/Camera.ts
@@ -1,50 +1,58 @@
import type { App } from '../app';
+import { defineResource } from '../resource';
import { UICameraInfo, type UICameraData } from '../ui/UICameraInfo';
import { screenToWorld, worldToScreen, createInvVPCache } from '../ui/uiMath';
-const invVPCache = createInvVPCache();
+/**
+ * Per-App camera-space query API: screen<->world conversions, the world-space
+ * mouse position, and the active camera's world bounds.
+ *
+ * Reads the per-App {@link UICameraInfo} resource. Each App holds its own
+ * instance (published as the {@link CameraView} resource) and its own
+ * inverse-view-projection cache, so two Apps running at once never share a
+ * single cached `app` or clobber each other's cache.
+ */
+export class CameraViewApi {
+ private readonly invVPCache = createInvVPCache();
+
+ constructor(private readonly app_: App) {}
+
+ private cam(): UICameraData | null {
+ const cam = this.app_.getResource(UICameraInfo);
+ return cam.valid ? cam : null;
+ }
-let app_: App | null = null;
-
-export function initCameraAPI(app: App): void {
- app_ = app;
-}
-
-export function shutdownCameraAPI(): void {
- app_ = null;
-}
-
-function getCameraData(): UICameraData | null {
- if (!app_) return null;
- const cam = app_.getResource(UICameraInfo);
- return cam.valid ? cam : null;
-}
-
-export const CameraUtils = {
screenToWorld(screenX: number, screenY: number): { x: number; y: number } | null {
- const cam = getCameraData();
+ const cam = this.cam();
if (!cam) return null;
- invVPCache.update(cam.viewProjection);
- const invVP = invVPCache.getInverse(cam.viewProjection);
+ this.invVPCache.update(cam.viewProjection);
+ const invVP = this.invVPCache.getInverse(cam.viewProjection);
return screenToWorld(screenX, screenY, invVP, cam.vpX, cam.vpY, cam.vpW, cam.vpH);
- },
+ }
worldToScreen(worldX: number, worldY: number): { x: number; y: number } | null {
- const cam = getCameraData();
+ const cam = this.cam();
if (!cam) return null;
const [sx, sy] = worldToScreen(worldX, worldY, cam.viewProjection, cam.vpX, cam.vpY, cam.vpW, cam.vpH);
return { x: sx, y: sy };
- },
+ }
getWorldMousePosition(): { x: number; y: number } | null {
- const cam = getCameraData();
+ const cam = this.cam();
if (!cam) return null;
return { x: cam.worldMouseX, y: cam.worldMouseY };
- },
+ }
getWorldBounds(): { left: number; right: number; bottom: number; top: number } | null {
- const cam = getCameraData();
+ const cam = this.cam();
if (!cam) return null;
return { left: cam.worldLeft, right: cam.worldRight, bottom: cam.worldBottom, top: cam.worldTop };
- },
-};
+ }
+}
+
+/**
+ * Per-App camera-query API resource, published by `corePlugin`. Read it as
+ * `app.getResource(CameraView)` to convert screen<->world etc. (Named
+ * `CameraView` rather than `Camera` because `Camera` is the ECS component.)
+ */
+export const CameraView = defineResource<CameraViewApi>(null!, 'CameraView');
diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.ts
index ca971a76d..df671f743 100644
--- a/sdk/src/camera/CameraPlugin.ts
+++ b/sdk/src/camera/CameraPlugin.ts
@@ -33,11 +33,9 @@ interface CameraInfo {
cameraY: number;
}
-const cameraInfoPool_: CameraInfo[] = [];
-
-function acquireCameraInfo(index: number): CameraInfo {
- if (index < cameraInfoPool_.length) {
- return cameraInfoPool_[index];
+function acquireCameraInfo(pool: CameraInfo[], index: number): CameraInfo {
+ if (index < pool.length) {
+ return pool[index];
}
const info: CameraInfo = {
entity: 0,
@@ -50,7 +48,7 @@ function acquireCameraInfo(index: number): CameraInfo {
cameraX: 0,
cameraY: 0,
};
- cameraInfoPool_.push(info);
+ pool.push(info);
return info;
}
@@ -98,6 +96,7 @@ export function collectCameras(
height: number,
world?: World,
activeScenes?: Set<string>,
+ pool: CameraInfo[] = [],
): CameraInfo[] {
if (width === 0 || height === 0) return [];
const cameraEntities = module.registry_getCameraEntities(registry);
@@ -148,7 +147,7 @@ export function collectCameras(
}
const view = invertTranslation(transform.position.x, transform.position.y, transform.position.z);
- const cam = acquireCameraInfo(cameras.length);
+ const cam = acquireCameraInfo(pool, cameras.length);
cam.entity = e;
cam.viewProjection.set(multiply(projection, view));
cam.viewportRect.x = camera.viewport.x;
@@ -179,9 +178,10 @@ function syncUICameraInfo(
width: number,
height: number,
cameras?: CameraInfo[],
+ pool?: CameraInfo[],
): void {
if (!cameras) {
- cameras = collectCameras(module, cppRegistry, width, height);
+ cameras = collectCameras(module, cppRegistry, width, height, undefined, undefined, pool);
}
const uiCam = app.getResource(UICameraInfo);
if (cameras.length > 0) {
@@ -218,6 +218,9 @@ export function cameraPlugin(
const cppRegistry = app.world.getCppRegistry()!;
const pipeline = app.pipeline!;
const startTime = platformNow();
+ // Per-App scratch pool for collectCameras — one per plugin instance,
+ // so two Apps running at once never clobber each other's CameraInfo.
+ const cameraInfoPool: CameraInfo[] = [];
const viewport = getViewportSize ?? (() => {
const dpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;
@@ -233,7 +236,7 @@ export function cameraPlugin(
_params: [],
_fn: () => {
const { width, height } = viewport();
- syncUICameraInfo(app, module, cppRegistry, width, height);
+ syncUICameraInfo(app, module, cppRegistry, width, height, undefined, cameraInfoPool);
},
};
@@ -264,7 +267,7 @@ export function cameraPlugin(
}
pipeline.setActiveScenes(activeScenes ?? null);
- const cameras = collectCameras(module, cppRegistry, width, height, app.world, activeScenes);
+ const cameras = collectCameras(module, cppRegistry, width, height, app.world, activeScenes, cameraInfoPool);
syncUICameraInfo(app, module, cppRegistry, width, height, cameras);
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 5f13549d7..b0740d066 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -37,7 +37,7 @@ export { TextureFilter, TextureWrap, setTextureFilter, setTextureWrap, setTextur
// Camera
// =============================================================================
-export { CameraUtils } from './camera/Camera';
+export { CameraView, CameraViewApi } from './camera/Camera';
// =============================================================================
// Draw API
diff --git a/sdk/src/corePlugin.ts b/sdk/src/corePlugin.ts
index 07c547415..aa75e1e05 100644
--- a/sdk/src/corePlugin.ts
+++ b/sdk/src/corePlugin.ts
@@ -7,7 +7,7 @@ import { initGeometryAPI, shutdownGeometryAPI } from './geometry';
import { initPostProcessAPI, shutdownPostProcessAPI } from './postprocess';
import { initRendererAPI, shutdownRendererAPI } from './renderer';
import { initGLDebugAPI, shutdownGLDebugAPI } from './glDebug';
-import { initCameraAPI, shutdownCameraAPI } from './camera/Camera';
+import { CameraView, CameraViewApi } from './camera/Camera';
export const corePlugin: Plugin = {
name: 'engineCore',
@@ -21,12 +21,11 @@ export const corePlugin: Plugin = {
initPostProcessAPI(module);
initRendererAPI(module);
initGLDebugAPI(module);
- initCameraAPI(app);
+ app.insertResource(CameraView, new CameraViewApi(app));
},
cleanup() {
clearDrawCallbacks();
- shutdownCameraAPI();
shutdownGLDebugAPI();
shutdownRendererAPI();
shutdownPostProcessAPI();
diff --git a/sdk/tests/camera-utils.test.ts b/sdk/tests/camera-utils.test.ts
index 2d37103bb..8b0dfeec7 100644
--- a/sdk/tests/camera-utils.test.ts
+++ b/sdk/tests/camera-utils.test.ts
@@ -1,5 +1,5 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { CameraUtils, initCameraAPI, shutdownCameraAPI } from '../src/camera/Camera';
+import { describe, it, expect, vi } from 'vitest';
+import { CameraViewApi } from '../src/camera/Camera';
const mockUICameraData = {
viewProjection: new Float32Array([
@@ -23,74 +23,51 @@ const mockUICameraData = {
valid: true,
};
-function createMockApp(cameraData = mockUICameraData) {
- return {
- getResource: vi.fn(() => cameraData),
- } as any;
+function makeCamera(cameraData = mockUICameraData): CameraViewApi {
+ const app = { getResource: vi.fn(() => cameraData) } as any;
+ return new CameraViewApi(app);
}
-describe('CameraUtils', () => {
- afterEach(() => {
- shutdownCameraAPI();
+describe('CameraViewApi', () => {
+ it('returns null when the camera is invalid', () => {
+ const cam = makeCamera({ ...mockUICameraData, valid: false });
+ expect(cam.screenToWorld(400, 300)).toBeNull();
+ expect(cam.worldToScreen(0, 0)).toBeNull();
+ expect(cam.getWorldMousePosition()).toBeNull();
+ expect(cam.getWorldBounds()).toBeNull();
});
- it('should return null when not initialized', () => {
- expect(CameraUtils.screenToWorld(400, 300)).toBeNull();
- expect(CameraUtils.worldToScreen(0, 0)).toBeNull();
- expect(CameraUtils.getWorldMousePosition()).toBeNull();
- expect(CameraUtils.getWorldBounds()).toBeNull();
- });
-
- it('should return null when camera is invalid', () => {
- const app = createMockApp({ ...mockUICameraData, valid: false });
- initCameraAPI(app);
-
- expect(CameraUtils.screenToWorld(400, 300)).toBeNull();
- expect(CameraUtils.worldToScreen(0, 0)).toBeNull();
- });
-
- it('should convert screen center to world origin with identity VP', () => {
- initCameraAPI(createMockApp());
-
- const result = CameraUtils.screenToWorld(400, 300);
+ it('converts screen center to world origin with identity VP', () => {
+ const result = makeCamera().screenToWorld(400, 300);
expect(result).not.toBeNull();
expect(result!.x).toBeCloseTo(0, 1);
expect(result!.y).toBeCloseTo(0, 1);
});
- it('should convert world origin back to screen center', () => {
- initCameraAPI(createMockApp());
-
- const result = CameraUtils.worldToScreen(0, 0);
+ it('converts world origin back to screen center', () => {
+ const result = makeCamera().worldToScreen(0, 0);
expect(result).not.toBeNull();
expect(result!.x).toBeCloseTo(400, 0);
expect(result!.y).toBeCloseTo(300, 0);
});
- it('should return world mouse position', () => {
- initCameraAPI(createMockApp());
-
- const result = CameraUtils.getWorldMousePosition();
- expect(result).toEqual({ x: 50, y: -25 });
+ it('returns the world mouse position', () => {
+ expect(makeCamera().getWorldMousePosition()).toEqual({ x: 50, y: -25 });
});
- it('should return world bounds', () => {
- initCameraAPI(createMockApp());
-
- const bounds = CameraUtils.getWorldBounds();
- expect(bounds).toEqual({
- left: -400,
- right: 400,
- bottom: -300,
- top: 300,
+ it('returns the world bounds', () => {
+ expect(makeCamera().getWorldBounds()).toEqual({
+ left: -400, right: 400, bottom: -300, top: 300,
});
});
- it('should return null after shutdown', () => {
- initCameraAPI(createMockApp());
- expect(CameraUtils.getWorldMousePosition()).not.toBeNull();
-
- shutdownCameraAPI();
- expect(CameraUtils.getWorldMousePosition()).toBeNull();
+ // The whole point of F3: two Apps each have their own CameraViewApi reading
+ // their own UICameraInfo — no shared global `app_` to bleed between them.
+ it('is isolated per App', () => {
+ const a = makeCamera({ ...mockUICameraData, worldMouseX: 1, worldMouseY: 2 });
+ const b = makeCamera({ ...mockUICameraData, worldMouseX: 9, worldMouseY: 8 });
+ expect(a.getWorldMousePosition()).toEqual({ x: 1, y: 2 });
+ expect(b.getWorldMousePosition()).toEqual({ x: 9, y: 8 });
+ expect(a.getWorldMousePosition()).toEqual({ x: 1, y: 2 });
});
});