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.

feat: unified render pipeline with custom draw support

esengine9d1926b099a4
diff --git a/desktop/public/sdk/esm/index.d.ts b/desktop/public/sdk/esm/index.d.ts
index de4ba80a4..b50e4ba13 100644
--- a/desktop/public/sdk/esm/index.d.ts
+++ b/desktop/public/sdk/esm/index.d.ts
@@ -76,6 +76,7 @@ interface SpriteData {
layer: number;
flipX: boolean;
flipY: boolean;
+ material: number;
}
interface CameraData {
projectionType: number;
@@ -117,6 +118,7 @@ interface SpineAnimationData {
color: Vec4;
layer: number;
skeletonScale: number;
+ material: number;
}
declare const LocalTransform: BuiltinComponentDef<LocalTransformData>;
declare const WorldTransform: BuiltinComponentDef<WorldTransformData>;
@@ -128,6 +130,7 @@ declare const Parent: BuiltinComponentDef<ParentData>;
declare const Children: BuiltinComponentDef<ChildrenData>;
declare const SpineAnimation: BuiltinComponentDef<SpineAnimationData>;
type ComponentData<C> = C extends BuiltinComponentDef<infer T> ? T : C extends ComponentDef<infer T> ? T : never;
+declare function getComponentDefaults(typeName: string): Record<string, unknown> | null;
/**
* @file resource.ts
@@ -268,8 +271,11 @@ interface SpineBounds {
interface ESEngineModule {
Registry: new () => CppRegistry;
HEAPU8: Uint8Array;
+ HEAPU32: Uint32Array;
HEAPF32: Float32Array;
FS: EmscriptenFS;
+ addFunction(func: (...args: any[]) => any, signature: string): number;
+ setMaterialCallback(callbackPtr: number): void;
initRenderer(): void;
initRendererWithCanvas(canvasSelector: string): boolean;
initRendererWithContext(contextHandle: number): boolean;
@@ -285,6 +291,62 @@ interface ESEngineModule {
renderFrameWithMatrix(registry: CppRegistry, width: number, height: number, matrixPtr: number): void;
getResourceManager(): CppResourceManager;
getSpineBounds(registry: CppRegistry, entity: number): SpineBounds;
+ draw_begin(matrixPtr: number): void;
+ draw_end(): void;
+ draw_line(fromX: number, fromY: number, toX: number, toY: number, r: number, g: number, b: number, a: number, thickness: number): void;
+ draw_rect(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, filled: boolean): void;
+ draw_rectOutline(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number, thickness: number): void;
+ draw_circle(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, filled: boolean, segments: number): void;
+ draw_circleOutline(centerX: number, centerY: number, radius: number, r: number, g: number, b: number, a: number, thickness: number, segments: number): void;
+ draw_texture(x: number, y: number, width: number, height: number, textureId: number, r: number, g: number, b: number, a: number): void;
+ draw_textureRotated(x: number, y: number, width: number, height: number, rotation: number, textureId: number, r: number, g: number, b: number, a: number): void;
+ draw_setLayer(layer: number): void;
+ draw_setDepth(depth: number): void;
+ draw_getDrawCallCount(): number;
+ draw_getPrimitiveCount(): number;
+ draw_setBlendMode(mode: number): void;
+ draw_setDepthTest(enabled: boolean): void;
+ draw_mesh(geometryHandle: number, shaderHandle: number, transformPtr: number): void;
+ draw_meshWithUniforms(geometryHandle: number, shaderHandle: number, transformPtr: number, uniformsPtr: number, uniformCount: number): void;
+ geometry_create(): number;
+ geometry_init(handle: number, verticesPtr: number, vertexCount: number, layoutPtr: number, layoutCount: number, dynamic: boolean): void;
+ geometry_setIndices16(handle: number, indicesPtr: number, indexCount: number): void;
+ geometry_setIndices32(handle: number, indicesPtr: number, indexCount: number): void;
+ geometry_updateVertices(handle: number, verticesPtr: number, vertexCount: number, offset: number): void;
+ geometry_release(handle: number): void;
+ geometry_isValid(handle: number): boolean;
+ postprocess_init(width: number, height: number): boolean;
+ postprocess_shutdown(): void;
+ postprocess_resize(width: number, height: number): void;
+ postprocess_addPass(name: string, shaderHandle: number): number;
+ postprocess_removePass(name: string): void;
+ postprocess_setPassEnabled(name: string, enabled: boolean): void;
+ postprocess_isPassEnabled(name: string): boolean;
+ postprocess_setUniformFloat(passName: string, uniform: string, value: number): void;
+ postprocess_setUniformVec4(passName: string, uniform: string, x: number, y: number, z: number, w: number): void;
+ postprocess_begin(): void;
+ postprocess_end(): void;
+ postprocess_getPassCount(): number;
+ postprocess_isInitialized(): boolean;
+ postprocess_setBypass(bypass: boolean): void;
+ postprocess_isBypassed(): boolean;
+ renderer_init(width: number, height: number): void;
+ renderer_resize(width: number, height: number): void;
+ renderer_begin(matrixPtr: number, targetHandle: number): void;
+ renderer_end(): void;
+ renderer_submitSprites(registry: CppRegistry): void;
+ renderer_submitSpine(registry: CppRegistry): void;
+ renderer_setStage(stage: number): void;
+ renderer_createTarget(width: number, height: number): number;
+ renderer_releaseTarget(handle: number): void;
+ renderer_getTargetTexture(handle: number): number;
+ renderer_getDrawCalls(): number;
+ renderer_getTriangles(): number;
+ renderer_getSprites(): number;
+ renderer_getSpine(): number;
+ renderer_getMeshes(): number;
+ renderer_getCulled(): number;
+ renderer_setClearColor(r: number, g: number, b: number, a: number): void;
_malloc(size: number): number;
_free(ptr: number): void;
}
@@ -306,6 +368,7 @@ declare class World {
entityCount(): number;
getAllEntities(): Entity[];
setParent(child: Entity, parent: Entity): void;
+ removeParent(entity: Entity): void;
insert(entity: Entity, component: AnyComponentDef, data?: unknown): unknown;
get(entity: Entity, component: AnyComponentDef): unknown;
has(entity: Entity, component: AnyComponentDef): boolean;
@@ -579,52 +642,187 @@ declare class TextPlugin implements Plugin {
declare const textPlugin: TextPlugin;
/**
- * @file AssetServer.ts
- * @brief Asset loading and caching system
+ * @file blend.ts
+ * @brief Blend mode definitions for rendering
*/
+declare enum BlendMode {
+ Normal = 0,
+ Additive = 1,
+ Multiply = 2,
+ Screen = 3,
+ PremultipliedAlpha = 4
+}
-interface TextureInfo {
- handle: TextureHandle;
- width: number;
- height: number;
+/**
+ * @file material.ts
+ * @brief Material and Shader API for custom rendering
+ * @details Provides shader creation and material management for custom visual effects.
+ */
+
+type ShaderHandle = number;
+type MaterialHandle = number;
+type UniformValue = number | Vec2 | Vec3 | Vec4 | number[];
+interface MaterialOptions {
+ shader: ShaderHandle;
+ uniforms?: Record<string, UniformValue>;
+ blendMode?: BlendMode;
+ depthTest?: boolean;
+}
+interface MaterialAssetData {
+ version: string;
+ type: 'material';
+ shader: string;
+ blendMode: number;
+ depthTest: boolean;
+ properties: Record<string, unknown>;
+}
+interface MaterialData {
+ shader: ShaderHandle;
+ uniforms: Map<string, UniformValue>;
+ blendMode: BlendMode;
+ depthTest: boolean;
+}
+declare function initMaterialAPI(wasmModule: ESEngineModule): void;
+declare function shutdownMaterialAPI(): void;
+declare const Material: {
+ /**
+ * Creates a shader from vertex and fragment source code.
+ * @param vertexSrc GLSL vertex shader source
+ * @param fragmentSrc GLSL fragment shader source
+ * @returns Shader handle, or 0 on failure
+ */
+ createShader(vertexSrc: string, fragmentSrc: string): ShaderHandle;
+ /**
+ * Releases a shader.
+ * @param shader Shader handle to release
+ */
+ releaseShader(shader: ShaderHandle): void;
+ /**
+ * Creates a material with a shader and optional settings.
+ * @param options Material creation options
+ * @returns Material handle
+ */
+ create(options: MaterialOptions): MaterialHandle;
+ /**
+ * Gets material data by handle.
+ * @param material Material handle
+ * @returns Material data or undefined
+ */
+ get(material: MaterialHandle): MaterialData | undefined;
+ /**
+ * Sets a uniform value on a material.
+ * @param material Material handle
+ * @param name Uniform name
+ * @param value Uniform value
+ */
+ setUniform(material: MaterialHandle, name: string, value: UniformValue): void;
+ /**
+ * Gets a uniform value from a material.
+ * @param material Material handle
+ * @param name Uniform name
+ * @returns Uniform value or undefined
+ */
+ getUniform(material: MaterialHandle, name: string): UniformValue | undefined;
+ /**
+ * Sets the blend mode for a material.
+ * @param material Material handle
+ * @param mode Blend mode
+ */
+ setBlendMode(material: MaterialHandle, mode: BlendMode): void;
+ /**
+ * Gets the blend mode of a material.
+ * @param material Material handle
+ * @returns Blend mode
+ */
+ getBlendMode(material: MaterialHandle): BlendMode;
+ /**
+ * Sets depth test enabled for a material.
+ * @param material Material handle
+ * @param enabled Whether depth test is enabled
+ */
+ setDepthTest(material: MaterialHandle, enabled: boolean): void;
+ /**
+ * Gets the shader handle for a material.
+ * @param material Material handle
+ * @returns Shader handle
+ */
+ getShader(material: MaterialHandle): ShaderHandle;
+ /**
+ * Releases a material (does not release the shader).
+ * @param material Material handle
+ */
+ release(material: MaterialHandle): void;
+ /**
+ * Checks if a material exists.
+ * @param material Material handle
+ * @returns True if material exists
+ */
+ isValid(material: MaterialHandle): boolean;
+ /**
+ * Creates a material from asset data.
+ * @param data Material asset data (properties object)
+ * @param shaderHandle Pre-loaded shader handle
+ * @returns Material handle
+ */
+ createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle): MaterialHandle;
+ /**
+ * Creates a material instance that shares the shader with source.
+ * @param source Source material handle
+ * @returns New material handle with copied settings
+ */
+ createInstance(source: MaterialHandle): MaterialHandle;
+ /**
+ * Exports material to serializable asset data.
+ * @param material Material handle
+ * @param shaderPath Shader file path for asset reference
+ * @returns Material asset data
+ */
+ toAssetData(material: MaterialHandle, shaderPath: string): MaterialAssetData | null;
+ /**
+ * Gets all uniforms from a material.
+ * @param material Material handle
+ * @returns Map of uniform names to values
+ */
+ getUniforms(material: MaterialHandle): Map<string, UniformValue>;
+};
+declare function registerMaterialCallback(): void;
+declare const ShaderSources: {
+ SPRITE_VERTEX: string;
+ SPRITE_FRAGMENT: string;
+ COLOR_VERTEX: string;
+ COLOR_FRAGMENT: string;
+};
+
+/**
+ * @file MaterialLoader.ts
+ * @brief Material asset loading and caching
+ */
+
+interface LoadedMaterial {
+ handle: MaterialHandle;
+ shaderHandle: ShaderHandle;
+ path: string;
}
-interface SliceBorder$1 {
- left: number;
- right: number;
- top: number;
- bottom: number;
+interface ShaderLoader {
+ load(path: string): Promise<ShaderHandle>;
+ get(path: string): ShaderHandle | undefined;
}
-declare class AssetServer {
- private module_;
+declare class MaterialLoader {
private cache_;
private pending_;
- private canvas_;
- private ctx_;
- constructor(module: ESEngineModule);
- loadTexture(source: string): Promise<TextureInfo>;
- getTexture(source: string): TextureInfo | undefined;
- hasTexture(source: string): boolean;
- releaseTexture(source: string): void;
+ private shaderLoader_;
+ private basePath_;
+ constructor(shaderLoader: ShaderLoader, basePath?: string);
+ load(path: string): Promise<LoadedMaterial>;
+ get(path: string): LoadedMaterial | undefined;
+ has(path: string): boolean;
+ release(path: string): void;
releaseAll(): void;
- setTextureMetadata(handle: TextureHandle, border: SliceBorder$1): void;
- setTextureMetadataByPath(source: string, border: SliceBorder$1): boolean;
- private loadTextureInternal;
- private loadImage;
- private createTextureFromImage;
- private unpremultiplyAlpha;
- private flipVertically;
- private nextPowerOf2;
+ private loadInternal;
+ private resolvePath;
+ private resolveShaderPath;
}
-interface AssetsData {
- server: AssetServer;
-}
-declare const Assets: ResourceDef<AssetsData>;
-declare class AssetPlugin implements Plugin {
- build(app: App): void;
-}
-declare const assetPlugin: AssetPlugin;
-
/**
* @file scene.ts
* @brief Scene loading utilities
@@ -641,7 +839,7 @@ interface SceneComponentData {
type: string;
data: Record<string, unknown>;
}
-interface SliceBorder {
+interface SliceBorder$1 {
left: number;
right: number;
top: number;
@@ -650,7 +848,7 @@ interface SliceBorder {
interface TextureMetadata {
version: string;
type: 'texture';
- sliceBorder: SliceBorder;
+ sliceBorder: SliceBorder$1;
}
interface SceneData {
version: string;
@@ -664,8 +862,132 @@ interface SceneLoadOptions {
}
declare function loadSceneData(world: World, sceneData: SceneData): Map<number, Entity>;
declare function loadSceneWithAssets(world: World, sceneData: SceneData, options?: SceneLoadOptions): Promise<Map<number, Entity>>;
+declare function loadComponent(world: World, entity: Entity, compData: SceneComponentData): void;
declare function updateCameraAspectRatio(world: World, aspectRatio: number): void;
+/**
+ * @file AssetServer.ts
+ * @brief Asset loading and caching system
+ */
+
+interface TextureInfo {
+ handle: TextureHandle;
+ width: number;
+ height: number;
+}
+interface SliceBorder {
+ left: number;
+ right: number;
+ top: number;
+ bottom: number;
+}
+interface SpineLoadResult {
+ success: boolean;
+ error?: string;
+}
+interface SpineDescriptor {
+ skeleton: string;
+ atlas: string;
+ baseUrl?: string;
+}
+interface FileLoadOptions {
+ baseUrl?: string;
+ noCache?: boolean;
+}
+interface AssetManifest {
+ textures?: string[];
+ materials?: string[];
+ spine?: SpineDescriptor[];
+ json?: string[];
+ text?: string[];
+ binary?: string[];
+}
+interface AssetBundle {
+ textures: Map<string, TextureInfo>;
+ materials: Map<string, LoadedMaterial>;
+ spine: Map<string, SpineLoadResult>;
+ json: Map<string, unknown>;
+ text: Map<string, string>;
+ binary: Map<string, ArrayBuffer>;
+}
+declare class AssetServer {
+ baseUrl?: string;
+ private module_;
+ private textureCache_;
+ private shaderCache_;
+ private jsonCache_;
+ private textCache_;
+ private binaryCache_;
+ private loadedSpines_;
+ private virtualFSPaths_;
+ private materialLoader_;
+ private canvas_;
+ private ctx_;
+ constructor(module: ESEngineModule);
+ /**
+ * Load texture with vertical flip (for Sprite/UI).
+ * OpenGL UV origin is bottom-left, so standard images need flipping.
+ */
+ loadTexture(source: string): Promise<TextureInfo>;
+ /**
+ * Load texture without flip (for Spine).
+ * Spine runtime handles UV coordinates internally.
+ */
+ loadTextureRaw(source: string): Promise<TextureInfo>;
+ getTexture(source: string): TextureInfo | undefined;
+ hasTexture(source: string): boolean;
+ releaseTexture(source: string): void;
+ releaseAll(): void;
+ setTextureMetadata(handle: TextureHandle, border: SliceBorder): void;
+ setTextureMetadataByPath(source: string, border: SliceBorder): boolean;
+ loadSpine(skeletonPath: string, atlasPath: string, baseUrl?: string): Promise<SpineLoadResult>;
+ isSpineLoaded(skeletonPath: string, atlasPath: string): boolean;
+ loadMaterial(path: string, baseUrl?: string): Promise<LoadedMaterial>;
+ getMaterial(path: string, baseUrl?: string): LoadedMaterial | undefined;
+ hasMaterial(path: string, baseUrl?: string): boolean;
+ loadShader(path: string): Promise<ShaderHandle>;
+ loadJson<T = unknown>(path: string, options?: FileLoadOptions): Promise<T>;
+ loadText(path: string, options?: FileLoadOptions): Promise<string>;
+ loadBinary(path: string, options?: FileLoadOptions): Promise<ArrayBuffer>;
+ loadScene(world: World, sceneData: SceneData): Promise<Map<number, Entity>>;
+ loadAll(manifest: AssetManifest): Promise<AssetBundle>;
+ private textureCacheKey;
+ private loadTextureWithFlip;
+ private loadTextureInternal;
+ private loadImage;
+ private createTextureFromImage;
+ private unpremultiplyAlpha;
+ private loadShaderInternal;
+ private parseEsShader;
+ private fetchJson;
+ private fetchText;
+ private fetchBinary;
+ private writeToVirtualFS;
+ private ensureVirtualDir;
+ private resolveUrl;
+ private createCanvas;
+ private nextPowerOf2;
+ private parseAtlasTextures;
+}
+
+declare class AsyncCache<T> {
+ private cache_;
+ private pending_;
+ getOrLoad(key: string, loader: () => Promise<T>): Promise<T>;
+ get(key: string): T | undefined;
+ has(key: string): boolean;
+ delete(key: string): boolean;
+ clear(): void;
+ values(): IterableIterator<T>;
+}
+
+type AssetsData = AssetServer;
+declare const Assets: ResourceDef<AssetServer>;
+declare class AssetPlugin implements Plugin {
+ build(app: App): void;
+}
+declare const assetPlugin: AssetPlugin;
+
/**
* @file PreviewPlugin.ts
* @brief Plugin for editor preview functionality
@@ -969,5 +1291,390 @@ declare class SpineController {
*/
declare function createSpineController(wasmModule: any): SpineController;
-export { App, AssetPlugin, AssetServer, Assets, Camera, Canvas, Children, Commands, CommandsInstance, EntityCommands, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Mut, Parent, PreviewPlugin, Query, QueryInstance, Res, ResMut, ResMutInstance, Schedule, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getPlatform, getPlatformType, isBuiltinComponent, isPlatformInitialized, isWeChat, isWeb, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, textPlugin, updateCameraAspectRatio, vec2, vec3, vec4 };
-export type { AnyComponentDef, AssetsData, BuiltinComponentDef, CameraData, CanvasData, ChildrenData, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, ESEngineModule, Entity, InferParam, InferParams, InputState, LocalTransformData, MutWrapper, ParentData, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, Quat, QueryDescriptor, QueryResult, ResDescriptor, ResMutDescriptor, ResourceDef, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, SpineAnimationData, SpineEvent, SpineEventCallback, SpineEventType, SpriteData, SystemDef, SystemParam, TextData, TextRenderResult, TextureHandle, TextureInfo, TimeData, TrackEntryInfo, UIRectData, Vec2, Vec3, Vec4, VelocityData, WebAppOptions, WorldTransformData };
+/**
+ * @file geometry.ts
+ * @brief Geometry API for custom mesh rendering
+ * @details Provides geometry creation and management for custom shapes,
+ * particles, trails, and other procedural meshes.
+ */
+
+type GeometryHandle = number;
+declare enum DataType {
+ Float = 1,
+ Float2 = 2,
+ Float3 = 3,
+ Float4 = 4,
+ Int = 5,
+ Int2 = 6,
+ Int3 = 7,
+ Int4 = 8
+}
+interface VertexAttributeDescriptor {
+ name: string;
+ type: DataType;
+}
+interface GeometryOptions {
+ vertices: Float32Array;
+ layout: VertexAttributeDescriptor[];
+ indices?: Uint16Array | Uint32Array;
+ dynamic?: boolean;
+}
+declare function initGeometryAPI(wasmModule: ESEngineModule): void;
+declare function shutdownGeometryAPI(): void;
+declare const Geometry: {
+ /**
+ * Creates a new geometry with vertices and optional indices.
+ * @param options Geometry creation options
+ * @returns Geometry handle
+ */
+ create(options: GeometryOptions): GeometryHandle;
+ /**
+ * Updates vertices of a dynamic geometry.
+ * @param handle Geometry handle
+ * @param vertices New vertex data
+ * @param offset Offset in floats
+ */
+ updateVertices(handle: GeometryHandle, vertices: Float32Array, offset?: number): void;
+ /**
+ * Releases a geometry.
+ * @param handle Geometry handle
+ */
+ release(handle: GeometryHandle): void;
+ /**
+ * Checks if a geometry handle is valid.
+ * @param handle Geometry handle
+ * @returns True if valid
+ */
+ isValid(handle: GeometryHandle): boolean;
+ /**
+ * Creates a unit quad geometry (1x1, centered at origin).
+ * @returns Geometry handle
+ */
+ createQuad(width?: number, height?: number): GeometryHandle;
+ /**
+ * Creates a circle geometry.
+ * @param radius Circle radius
+ * @param segments Number of segments
+ * @returns Geometry handle
+ */
+ createCircle(radius?: number, segments?: number): GeometryHandle;
+ /**
+ * Creates a polygon geometry from vertices.
+ * @param points Array of {x, y} points
+ * @returns Geometry handle
+ */
+ createPolygon(points: Array<{
+ x: number;
+ y: number;
+ }>): GeometryHandle;
+};
+
+/**
+ * @file draw.ts
+ * @brief Immediate mode 2D drawing API
+ * @details Provides simple drawing primitives (lines, rectangles, circles)
+ * with automatic batching. All draw commands are cleared each frame.
+ */
+
+declare function initDrawAPI(wasmModule: ESEngineModule): void;
+declare function shutdownDrawAPI(): void;
+interface DrawAPI {
+ /**
+ * Begins a new draw frame with the given view-projection matrix.
+ * Must be called before any draw commands.
+ */
+ begin(viewProjection: Float32Array): void;
+ /**
+ * Ends the current draw frame and submits all commands.
+ * Must be called after all draw commands.
+ */
+ end(): void;
+ /**
+ * Draws a line between two points.
+ * @param from Start point
+ * @param to End point
+ * @param color RGBA color
+ * @param thickness Line thickness in pixels (default: 1)
+ */
+ line(from: Vec2, to: Vec2, color: Color, thickness?: number): void;
+ /**
+ * Draws a filled or outlined rectangle.
+ * @param position Center position
+ * @param size Width and height
+ * @param color RGBA color
+ * @param filled If true draws filled, if false draws outline (default: true)
+ */
+ rect(position: Vec2, size: Vec2, color: Color, filled?: boolean): void;
+ /**
+ * Draws a rectangle outline.
+ * @param position Center position
+ * @param size Width and height
+ * @param color RGBA color
+ * @param thickness Line thickness in pixels (default: 1)
+ */
+ rectOutline(position: Vec2, size: Vec2, color: Color, thickness?: number): void;
+ /**
+ * Draws a filled or outlined circle.
+ * @param center Center position
+ * @param radius Circle radius
+ * @param color RGBA color
+ * @param filled If true draws filled, if false draws outline (default: true)
+ * @param segments Number of segments for approximation (default: 32)
+ */
+ circle(center: Vec2, radius: number, color: Color, filled?: boolean, segments?: number): void;
+ /**
+ * Draws a circle outline.
+ * @param center Center position
+ * @param radius Circle radius
+ * @param color RGBA color
+ * @param thickness Line thickness in pixels (default: 1)
+ * @param segments Number of segments for approximation (default: 32)
+ */
+ circleOutline(center: Vec2, radius: number, color: Color, thickness?: number, segments?: number): void;
+ /**
+ * Draws a textured quad.
+ * @param position Center position
+ * @param size Width and height
+ * @param textureHandle GPU texture handle
+ * @param tint Color tint (default: white)
+ */
+ texture(position: Vec2, size: Vec2, textureHandle: number, tint?: Color): void;
+ /**
+ * Draws a rotated textured quad.
+ * @param position Center position
+ * @param size Width and height
+ * @param rotation Rotation angle in radians
+ * @param textureHandle GPU texture handle
+ * @param tint Color tint (default: white)
+ */
+ textureRotated(position: Vec2, size: Vec2, rotation: number, textureHandle: number, tint?: Color): void;
+ /**
+ * Sets the current render layer.
+ * @param layer Layer index (higher layers render on top)
+ */
+ setLayer(layer: number): void;
+ /**
+ * Sets the current depth for sorting within a layer.
+ * @param depth Z depth value
+ */
+ setDepth(depth: number): void;
+ /**
+ * Gets the number of draw calls in the current/last frame.
+ */
+ getDrawCallCount(): number;
+ /**
+ * Gets the number of primitives drawn in the current/last frame.
+ */
+ getPrimitiveCount(): number;
+ /**
+ * Sets the blend mode for subsequent draw operations.
+ * @param mode The blend mode to use
+ */
+ setBlendMode(mode: BlendMode): void;
+ /**
+ * Enables or disables depth testing.
+ * @param enabled True to enable depth testing
+ */
+ setDepthTest(enabled: boolean): void;
+ /**
+ * Draws a custom mesh with a shader.
+ * @param geometry Geometry handle
+ * @param shader Shader handle
+ * @param transform Transform matrix (4x4, column-major)
+ */
+ drawMesh(geometry: GeometryHandle, shader: ShaderHandle, transform: Float32Array): void;
+ /**
+ * Draws a custom mesh with a material.
+ * @param geometry Geometry handle
+ * @param material Material handle
+ * @param transform Transform matrix (4x4, column-major)
+ */
+ drawMeshWithMaterial(geometry: GeometryHandle, material: MaterialHandle, transform: Float32Array): void;
+}
+declare const Draw: DrawAPI;
+
+/**
+ * @file postprocess.ts
+ * @brief Post-processing effects API
+ * @details Provides full-screen post-processing effects like blur, vignette, etc.
+ */
+
+declare function initPostProcessAPI(wasmModule: ESEngineModule): void;
+declare function shutdownPostProcessAPI(): void;
+declare const PostProcess: {
+ /**
+ * Initializes the post-processing pipeline.
+ * @param width Framebuffer width
+ * @param height Framebuffer height
+ * @returns True on success
+ */
+ init(width: number, height: number): boolean;
+ /**
+ * Shuts down the post-processing pipeline.
+ */
+ shutdown(): void;
+ /**
+ * Resizes the framebuffers.
+ * @param width New width
+ * @param height New height
+ */
+ resize(width: number, height: number): void;
+ /**
+ * Adds a post-processing pass.
+ * @param name Unique name for the pass
+ * @param shader Shader handle
+ * @returns Pass index
+ */
+ addPass(name: string, shader: ShaderHandle): number;
+ /**
+ * Removes a pass by name.
+ * @param name Pass name
+ */
+ removePass(name: string): void;
+ /**
+ * Enables or disables a pass.
+ * @param name Pass name
+ * @param enabled Whether to enable the pass
+ */
+ setEnabled(name: string, enabled: boolean): void;
+ /**
+ * Checks if a pass is enabled.
+ * @param name Pass name
+ * @returns True if enabled
+ */
+ isEnabled(name: string): boolean;
+ /**
+ * Sets a float uniform on a pass.
+ * @param passName Pass name
+ * @param uniform Uniform name
+ * @param value Float value
+ */
+ setUniform(passName: string, uniform: string, value: number): void;
+ /**
+ * Sets a vec4 uniform on a pass.
+ * @param passName Pass name
+ * @param uniform Uniform name
+ * @param value Vec4 value
+ */
+ setUniformVec4(passName: string, uniform: string, value: Vec4): void;
+ /**
+ * Begins rendering to the post-process pipeline.
+ * Call this before rendering your scene.
+ */
+ begin(): void;
+ /**
+ * Ends and processes all passes.
+ * Call this after rendering your scene.
+ */
+ end(): void;
+ /**
+ * Gets the number of passes.
+ */
+ getPassCount(): number;
+ /**
+ * Checks if the pipeline is initialized.
+ */
+ isInitialized(): boolean;
+ /**
+ * Sets bypass mode to skip FBO rendering entirely.
+ * When bypassed, begin()/end() become no-ops and scene renders directly to screen.
+ * Use this when no post-processing passes are needed for maximum performance.
+ * @param bypass Whether to bypass the pipeline
+ */
+ setBypass(bypass: boolean): void;
+ /**
+ * Checks if bypass mode is enabled.
+ * @returns True if bypassed
+ */
+ isBypassed(): boolean;
+ /**
+ * Creates a blur effect shader.
+ * @returns Shader handle
+ */
+ createBlur(): ShaderHandle;
+ /**
+ * Creates a vignette effect shader.
+ * @returns Shader handle
+ */
+ createVignette(): ShaderHandle;
+ /**
+ * Creates a grayscale effect shader.
+ * @returns Shader handle
+ */
+ createGrayscale(): ShaderHandle;
+ /**
+ * Creates a chromatic aberration effect shader.
+ * @returns Shader handle
+ */
+ createChromaticAberration(): ShaderHandle;
+};
+
+declare enum RenderStage {
+ Background = 0,
+ Opaque = 1,
+ Transparent = 2,
+ Overlay = 3
+}
+type RenderTargetHandle = number;
+interface RenderStats {
+ drawCalls: number;
+ triangles: number;
+ sprites: number;
+ spine: number;
+ meshes: number;
+ culled: number;
+}
+declare function initRendererAPI(wasmModule: ESEngineModule): void;
+declare function shutdownRendererAPI(): void;
+declare const Renderer: {
+ init(width: number, height: number): void;
+ resize(width: number, height: number): void;
+ begin(viewProjection: Float32Array, target?: RenderTargetHandle): void;
+ end(): void;
+ submitSprites(registry: {
+ _cpp: CppRegistry;
+ }): void;
+ submitSpine(registry: {
+ _cpp: CppRegistry;
+ }): void;
+ setStage(stage: RenderStage): void;
+ createRenderTarget(width: number, height: number): RenderTargetHandle;
+ releaseRenderTarget(handle: RenderTargetHandle): void;
+ getTargetTexture(handle: RenderTargetHandle): number;
+ setClearColor(r: number, g: number, b: number, a: number): void;
+ getStats(): RenderStats;
+};
+
+/**
+ * @file renderPipeline.ts
+ * @brief Unified render pipeline for runtime and editor
+ */
+
+interface RenderParams {
+ registry: {
+ _cpp: CppRegistry;
+ };
+ viewProjection: Float32Array;
+ width: number;
+ height: number;
+ elapsed: number;
+}
+declare class RenderPipeline {
+ render(params: RenderParams): void;
+}
+
+/**
+ * @file customDraw.ts
+ * @brief Custom draw callback registration for the render pipeline
+ */
+type DrawCallback = (elapsed: number) => void;
+declare function registerDrawCallback(id: string, fn: DrawCallback): void;
+declare function unregisterDrawCallback(id: string): void;
+declare function clearDrawCallbacks(): void;
+
+declare function setEditorMode(active: boolean): void;
+declare function isEditor(): boolean;
+declare function isRuntime(): boolean;
+
+export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, Renderer, Res, ResMut, ResMutInstance, Schedule, ShaderSources, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, clearDrawCallbacks, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getComponentDefaults, getPlatform, getPlatformType, initDrawAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isWeChat, isWeb, loadComponent, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4 };
+export type { AnyComponentDef, AssetBundle, AssetManifest, AssetsData, BuiltinComponentDef, CameraData, CanvasData, ChildrenData, Color, CommandsDescriptor, ComponentData, ComponentDef, CppRegistry, CppResourceManager, DrawAPI, DrawCallback, ESEngineModule, Entity, FileLoadOptions, GeometryHandle, GeometryOptions, InferParam, InferParams, InputState, LoadedMaterial, LocalTransformData, MaterialAssetData, MaterialHandle, MaterialOptions, MutWrapper, ParentData, PlatformAdapter, PlatformRequestOptions, PlatformResponse, PlatformType, Plugin, Quat, QueryDescriptor, QueryResult, RenderParams, RenderStats, RenderTargetHandle, ResDescriptor, ResMutDescriptor, ResourceDef, SceneComponentData, SceneData, SceneEntityData, SceneLoadOptions, ShaderHandle, ShaderLoader, SliceBorder, SpineAnimationData, SpineDescriptor, SpineEvent, SpineEventCallback, SpineEventType, SpineLoadResult, SpriteData, SystemDef, SystemParam, TextData, TextRenderResult, TextureHandle, TextureInfo, TimeData, TrackEntryInfo, UIRectData, UniformValue, Vec2, Vec3, Vec4, VelocityData, VertexAttributeDescriptor, WebAppOptions, WorldTransformData };
diff --git a/desktop/public/sdk/esm/index.js b/desktop/public/sdk/esm/index.js
index e73f58737..1b3ba834e 100644
--- a/desktop/public/sdk/esm/index.js
+++ b/desktop/public/sdk/esm/index.js
@@ -214,14 +214,15 @@ const WorldTransform = defineBuiltin('WorldTransform', {
scale: { x: 1, y: 1, z: 1 }
});
const Sprite = defineBuiltin('Sprite', {
- texture: 0,
+ texture: INVALID_TEXTURE,
color: { x: 1, y: 1, z: 1, w: 1 },
size: { x: 32, y: 32 },
uvOffset: { x: 0, y: 0 },
uvScale: { x: 1, y: 1 },
layer: 0,
flipX: false,
- flipY: false
+ flipY: false,
+ material: 0
});
const Camera = defineBuiltin('Camera', {
projectionType: 0,
@@ -262,8 +263,30 @@ const SpineAnimation = defineBuiltin('SpineAnimation', {
flipY: false,
color: { x: 1, y: 1, z: 1, w: 1 },
layer: 0,
- skeletonScale: 1.0
+ skeletonScale: 1.0,
+ material: 0
});
+// =============================================================================
+// Component Defaults Registry
+// =============================================================================
+const builtinComponents = {
+ LocalTransform,
+ WorldTransform,
+ Sprite,
+ Camera,
+ Canvas,
+ Velocity,
+ Parent,
+ Children,
+ SpineAnimation,
+};
+function getComponentDefaults(typeName) {
+ const component = builtinComponents[typeName];
+ if (component) {
+ return { ...component._default };
+ }
+ return null;
+}
/**
* @file resource.ts
@@ -716,6 +739,11 @@ class World {
this.cppRegistry_.setParent(child, parent);
}
}
+ removeParent(entity) {
+ if (this.cppRegistry_) {
+ this.cppRegistry_.removeParent(entity);
+ }
+ }
// =========================================================================
// Component Management
// =========================================================================
@@ -1159,7 +1187,7 @@ class TextPlugin {
continue;
if (!world.has(entity, Sprite)) {
world.insert(entity, Sprite, {
- texture: 0,
+ texture: INVALID_TEXTURE,
size: { x: 0, y: 0 },
color: { x: 1, y: 1, z: 1, w: 1 },
anchor: { x: 0.5, y: 0.5 },
@@ -1184,238 +1212,1875 @@ class TextPlugin {
const textPlugin = new TextPlugin();
/**
- * @file app.ts
- * @brief Application builder and web platform integration
+ * @file blend.ts
+ * @brief Blend mode definitions for rendering
+ */
+var BlendMode;
+(function (BlendMode) {
+ BlendMode[BlendMode["Normal"] = 0] = "Normal";
+ BlendMode[BlendMode["Additive"] = 1] = "Additive";
+ BlendMode[BlendMode["Multiply"] = 2] = "Multiply";
+ BlendMode[BlendMode["Screen"] = 3] = "Screen";
+ BlendMode[BlendMode["PremultipliedAlpha"] = 4] = "PremultipliedAlpha";
+})(BlendMode || (BlendMode = {}));
+
+/**
+ * @file material.ts
+ * @brief Material and Shader API for custom rendering
+ * @details Provides shader creation and material management for custom visual effects.
*/
// =============================================================================
-// App
+// Internal State
// =============================================================================
-class App {
- constructor() {
- this.systems_ = new Map();
- this.runner_ = null;
- this.running_ = false;
- this.lastTime_ = 0;
- this.module_ = null;
- this.mainLoop = () => {
- if (!this.running_) {
- return;
- }
- const now = performance.now();
- const deltaMs = now - this.lastTime_;
- this.lastTime_ = now;
- const delta = deltaMs / 1000;
- this.updateTime(delta);
- this.runSchedule(Schedule.First);
- this.runSchedule(Schedule.PreUpdate);
- this.runSchedule(Schedule.Update);
- this.runSchedule(Schedule.PostUpdate);
- this.runSchedule(Schedule.Last);
- requestAnimationFrame(this.mainLoop);
+let module$5 = null;
+let resourceManager = null;
+let nextMaterialId = 1;
+const materials = new Map();
+// =============================================================================
+// Initialization
+// =============================================================================
+function initMaterialAPI(wasmModule) {
+ module$5 = wasmModule;
+ resourceManager = wasmModule.getResourceManager();
+ registerMaterialCallback();
+}
+function shutdownMaterialAPI() {
+ if (uniformBuffer$1 !== 0 && module$5) {
+ module$5._free(uniformBuffer$1);
+ uniformBuffer$1 = 0;
+ }
+ materials.clear();
+ nextMaterialId = 1;
+ materialCallbackRegistered = false;
+ resourceManager = null;
+ module$5 = null;
+}
+// =============================================================================
+// Shader API
+// =============================================================================
+function getResourceManager() {
+ if (!resourceManager) {
+ throw new Error('Material API not initialized. Call initMaterialAPI() first.');
+ }
+ return resourceManager;
+}
+const Material = {
+ /**
+ * Creates a shader from vertex and fragment source code.
+ * @param vertexSrc GLSL vertex shader source
+ * @param fragmentSrc GLSL fragment shader source
+ * @returns Shader handle, or 0 on failure
+ */
+ createShader(vertexSrc, fragmentSrc) {
+ return getResourceManager().createShader(vertexSrc, fragmentSrc);
+ },
+ /**
+ * Releases a shader.
+ * @param shader Shader handle to release
+ */
+ releaseShader(shader) {
+ if (shader > 0) {
+ getResourceManager().releaseShader(shader);
+ }
+ },
+ /**
+ * Creates a material with a shader and optional settings.
+ * @param options Material creation options
+ * @returns Material handle
+ */
+ create(options) {
+ const handle = nextMaterialId++;
+ const data = {
+ shader: options.shader,
+ uniforms: new Map(),
+ blendMode: options.blendMode ?? BlendMode.Normal,
+ depthTest: options.depthTest ?? false,
};
- this.world_ = new World();
- this.resources_ = new ResourceStorage();
- for (const s of Object.values(Schedule)) {
- if (typeof s === 'number') {
- this.systems_.set(s, []);
+ if (options.uniforms) {
+ for (const [key, value] of Object.entries(options.uniforms)) {
+ data.uniforms.set(key, value);
}
}
- }
- static new() {
- return new App();
- }
- // =========================================================================
- // Plugins
- // =========================================================================
- addPlugin(plugin) {
- plugin.build(this);
- return this;
- }
- // =========================================================================
- // Systems
- // =========================================================================
- addSystemToSchedule(schedule, system) {
- this.systems_.get(schedule).push({ system });
- return this;
- }
- addSystem(system) {
- return this.addSystemToSchedule(Schedule.Update, system);
- }
- addStartupSystem(system) {
- return this.addSystemToSchedule(Schedule.Startup, system);
- }
- // =========================================================================
- // C++ Integration
- // =========================================================================
- connectCpp(cppRegistry, module) {
- this.world_.connectCpp(cppRegistry);
- if (module) {
- this.module_ = module;
+ materials.set(handle, data);
+ return handle;
+ },
+ /**
+ * Gets material data by handle.
+ * @param material Material handle
+ * @returns Material data or undefined
+ */
+ get(material) {
+ return materials.get(material);
+ },
+ /**
+ * Sets a uniform value on a material.
+ * @param material Material handle
+ * @param name Uniform name
+ * @param value Uniform value
+ */
+ setUniform(material, name, value) {
+ const data = materials.get(material);
+ if (data) {
+ data.uniforms.set(name, value);
}
- return this;
- }
- get wasmModule() {
- return this.module_;
- }
- // =========================================================================
- // World Access
- // =========================================================================
- get world() {
- return this.world_;
- }
- // =========================================================================
- // Resource Access
- // =========================================================================
- insertResource(resource, value) {
- this.resources_.insert(resource, value);
- return this;
- }
- getResource(resource) {
- return this.resources_.get(resource);
- }
- hasResource(resource) {
- return this.resources_.has(resource);
- }
- // =========================================================================
- // Run
- // =========================================================================
- run() {
- if (this.running_) {
- return;
+ },
+ /**
+ * Gets a uniform value from a material.
+ * @param material Material handle
+ * @param name Uniform name
+ * @returns Uniform value or undefined
+ */
+ getUniform(material, name) {
+ const data = materials.get(material);
+ return data?.uniforms.get(name);
+ },
+ /**
+ * Sets the blend mode for a material.
+ * @param material Material handle
+ * @param mode Blend mode
+ */
+ setBlendMode(material, mode) {
+ const data = materials.get(material);
+ if (data) {
+ data.blendMode = mode;
}
- this.running_ = true;
- this.runner_ = new SystemRunner(this.world_, this.resources_);
- this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0 });
- this.runSchedule(Schedule.Startup);
- this.lastTime_ = performance.now();
- this.mainLoop();
- }
- quit() {
- this.running_ = false;
- }
- // =========================================================================
- // Internal
- // =========================================================================
- runSchedule(schedule) {
- const systems = this.systems_.get(schedule);
- if (!systems || !this.runner_) {
- return;
+ },
+ /**
+ * Gets the blend mode of a material.
+ * @param material Material handle
+ * @returns Blend mode
+ */
+ getBlendMode(material) {
+ const data = materials.get(material);
+ return data?.blendMode ?? BlendMode.Normal;
+ },
+ /**
+ * Sets depth test enabled for a material.
+ * @param material Material handle
+ * @param enabled Whether depth test is enabled
+ */
+ setDepthTest(material, enabled) {
+ const data = materials.get(material);
+ if (data) {
+ data.depthTest = enabled;
}
- for (const entry of systems) {
- this.runner_.run(entry.system);
+ },
+ /**
+ * Gets the shader handle for a material.
+ * @param material Material handle
+ * @returns Shader handle
+ */
+ getShader(material) {
+ const data = materials.get(material);
+ return data?.shader ?? 0;
+ },
+ /**
+ * Releases a material (does not release the shader).
+ * @param material Material handle
+ */
+ release(material) {
+ materials.delete(material);
+ },
+ /**
+ * Checks if a material exists.
+ * @param material Material handle
+ * @returns True if material exists
+ */
+ isValid(material) {
+ return materials.has(material);
+ },
+ /**
+ * Creates a material from asset data.
+ * @param data Material asset data (properties object)
+ * @param shaderHandle Pre-loaded shader handle
+ * @returns Material handle
+ */
+ createFromAsset(data, shaderHandle) {
+ const uniforms = {};
+ for (const [key, value] of Object.entries(data.properties)) {
+ if (typeof value === 'number') {
+ uniforms[key] = value;
+ }
+ else if (typeof value === 'object' && value !== null) {
+ const obj = value;
+ if ('w' in obj) {
+ uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0, w: obj.w ?? 0 };
+ }
+ else if ('z' in obj) {
+ uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0, z: obj.z ?? 0 };
+ }
+ else if ('y' in obj) {
+ uniforms[key] = { x: obj.x ?? 0, y: obj.y ?? 0 };
+ }
+ }
}
- }
- updateTime(delta) {
- const time = this.resources_.get(Time);
- const newTime = {
- delta,
- elapsed: time.elapsed + delta,
- frameCount: time.frameCount + 1
+ return this.create({
+ shader: shaderHandle,
+ uniforms,
+ blendMode: data.blendMode ?? BlendMode.Normal,
+ depthTest: data.depthTest ?? false,
+ });
+ },
+ /**
+ * Creates a material instance that shares the shader with source.
+ * @param source Source material handle
+ * @returns New material handle with copied settings
+ */
+ createInstance(source) {
+ const sourceData = materials.get(source);
+ if (!sourceData) {
+ throw new Error(`Invalid source material: ${source}`);
+ }
+ const handle = nextMaterialId++;
+ const data = {
+ shader: sourceData.shader,
+ uniforms: new Map(sourceData.uniforms),
+ blendMode: sourceData.blendMode,
+ depthTest: sourceData.depthTest,
};
- this.resources_.set(Time, newTime);
- }
+ materials.set(handle, data);
+ return handle;
+ },
+ /**
+ * Exports material to serializable asset data.
+ * @param material Material handle
+ * @param shaderPath Shader file path for asset reference
+ * @returns Material asset data
+ */
+ toAssetData(material, shaderPath) {
+ const data = materials.get(material);
+ if (!data)
+ return null;
+ const properties = {};
+ for (const [key, value] of data.uniforms) {
+ properties[key] = value;
+ }
+ return {
+ version: '1.0',
+ type: 'material',
+ shader: shaderPath,
+ blendMode: data.blendMode,
+ depthTest: data.depthTest,
+ properties,
+ };
+ },
+ /**
+ * Gets all uniforms from a material.
+ * @param material Material handle
+ * @returns Map of uniform names to values
+ */
+ getUniforms(material) {
+ const data = materials.get(material);
+ return data ? new Map(data.uniforms) : new Map();
+ },
+};
+// =============================================================================
+// Material Callback Registration
+// =============================================================================
+let materialCallbackRegistered = false;
+let uniformBuffer$1 = 0;
+const UNIFORM_BUFFER_SIZE = 4096;
+function ensureUniformBuffer() {
+ if (uniformBuffer$1 === 0 && module$5) {
+ uniformBuffer$1 = module$5._malloc(UNIFORM_BUFFER_SIZE);
+ }
+ return uniformBuffer$1;
}
-function createWebApp(module, options) {
- const app = App.new();
- const cppRegistry = new module.Registry();
- app.connectCpp(cppRegistry, module);
- if (options?.glContextHandle) {
- module.initRendererWithContext(options.glContextHandle);
- }
- else {
- module.initRenderer();
+function serializeUniforms(uniforms) {
+ const bufferPtr = ensureUniformBuffer();
+ if (bufferPtr === 0 || !module$5)
+ return { ptr: 0, count: 0 };
+ let offset = 0;
+ let count = 0;
+ const heap8 = module$5.HEAPU8;
+ const heap32 = module$5.HEAPU32;
+ const heapF32 = module$5.HEAPF32;
+ for (const [name, value] of uniforms) {
+ if (offset + 128 > UNIFORM_BUFFER_SIZE)
+ break;
+ const nameBytes = new TextEncoder().encode(name);
+ const nameLen = nameBytes.length;
+ const namePadded = Math.ceil(nameLen / 4) * 4;
+ heap32[(bufferPtr + offset) >> 2] = nameLen;
+ offset += 4;
+ heap8.set(nameBytes, bufferPtr + offset);
+ offset += namePadded;
+ let type = 0;
+ let values = [0, 0, 0, 0];
+ if (typeof value === 'number') {
+ type = 0;
+ values[0] = value;
+ }
+ else if (Array.isArray(value)) {
+ type = Math.min(value.length - 1, 3);
+ for (let i = 0; i < Math.min(value.length, 4); i++) {
+ values[i] = value[i];
+ }
+ }
+ else if ('w' in value) {
+ type = 3;
+ values = [value.x, value.y, value.z, value.w];
+ }
+ else if ('z' in value) {
+ type = 2;
+ values = [value.x, value.y, value.z, 0];
+ }
+ else if ('y' in value) {
+ type = 1;
+ values = [value.x, value.y, 0, 0];
+ }
+ heap32[(bufferPtr + offset) >> 2] = type;
+ offset += 4;
+ for (let i = 0; i < 4; i++) {
+ heapF32[(bufferPtr + offset) >> 2] = values[i];
+ offset += 4;
+ }
+ count++;
}
- const getViewportSize = options?.getViewportSize ?? (() => ({
- width: window.innerWidth * (window.devicePixelRatio || 1),
- height: window.innerHeight * (window.devicePixelRatio || 1)
- }));
- const renderSystem = {
- _id: Symbol('RenderSystem'),
- _name: 'RenderSystem',
- _params: [],
- _fn: () => {
- const { width, height } = getViewportSize();
- module.renderFrame(cppRegistry, width, height);
+ return { ptr: bufferPtr, count };
+}
+function registerMaterialCallback() {
+ if (!module$5 || materialCallbackRegistered)
+ return;
+ if (!module$5.addFunction || !module$5.setMaterialCallback) {
+ console.warn('[Material] Callback registration not available (requires -sALLOW_TABLE_GROWTH)');
+ return;
+ }
+ const callback = (materialId, outShaderIdPtr, outBlendModePtr, outUniformBufferPtr, outUniformCountPtr) => {
+ const data = materials.get(materialId);
+ if (!data) {
+ module$5.HEAPU32[outShaderIdPtr >> 2] = 0;
+ module$5.HEAPU32[outBlendModePtr >> 2] = 0;
+ module$5.HEAPU32[outUniformBufferPtr >> 2] = 0;
+ module$5.HEAPU32[outUniformCountPtr >> 2] = 0;
+ return;
}
+ module$5.HEAPU32[outShaderIdPtr >> 2] = data.shader;
+ module$5.HEAPU32[outBlendModePtr >> 2] = data.blendMode;
+ const { ptr, count } = serializeUniforms(data.uniforms);
+ module$5.HEAPU32[outUniformBufferPtr >> 2] = ptr;
+ module$5.HEAPU32[outUniformCountPtr >> 2] = count;
};
- app.addSystemToSchedule(Schedule.Last, renderSystem);
- app.addPlugin(textPlugin);
- return app;
+ const callbackPtr = module$5.addFunction(callback, 'viiiii');
+ module$5.setMaterialCallback(callbackPtr);
+ materialCallbackRegistered = true;
+}
+// =============================================================================
+// Built-in Shader Sources
+// =============================================================================
+const ShaderSources = {
+ SPRITE_VERTEX: `#version 300 es
+precision highp float;
+
+layout(location = 0) in vec3 a_position;
+layout(location = 1) in vec4 a_color;
+layout(location = 2) in vec2 a_texCoord;
+
+uniform mat4 u_projection;
+uniform mat4 u_model;
+
+out vec4 v_color;
+out vec2 v_texCoord;
+
+void main() {
+ v_color = a_color;
+ v_texCoord = a_texCoord;
+ gl_Position = u_projection * u_model * vec4(a_position, 1.0);
+}
+`,
+ SPRITE_FRAGMENT: `#version 300 es
+precision highp float;
+
+in vec4 v_color;
+in vec2 v_texCoord;
+
+uniform sampler2D u_texture;
+
+out vec4 fragColor;
+
+void main() {
+ fragColor = texture(u_texture, v_texCoord) * v_color;
+}
+`,
+ COLOR_VERTEX: `#version 300 es
+precision highp float;
+
+layout(location = 0) in vec3 a_position;
+layout(location = 1) in vec4 a_color;
+
+uniform mat4 u_projection;
+uniform mat4 u_model;
+
+out vec4 v_color;
+
+void main() {
+ v_color = a_color;
+ gl_Position = u_projection * u_model * vec4(a_position, 1.0);
+}
+`,
+ COLOR_FRAGMENT: `#version 300 es
+precision highp float;
+
+in vec4 v_color;
+
+out vec4 fragColor;
+
+void main() {
+ fragColor = v_color;
}
+`,
+};
/**
- * @file AssetServer.ts
- * @brief Asset loading and caching system
+ * @file draw.ts
+ * @brief Immediate mode 2D drawing API
+ * @details Provides simple drawing primitives (lines, rectangles, circles)
+ * with automatic batching. All draw commands are cleared each frame.
*/
// =============================================================================
-// AssetServer
+// Internal State
// =============================================================================
-class AssetServer {
- constructor(module) {
- this.cache_ = new Map();
- this.pending_ = new Map();
- this.module_ = module;
- if (typeof OffscreenCanvas !== 'undefined') {
- this.canvas_ = new OffscreenCanvas(512, 512);
- this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });
- }
- else {
- this.canvas_ = document.createElement('canvas');
- this.canvas_.width = 512;
- this.canvas_.height = 512;
- this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });
+let module$4 = null;
+let viewProjectionPtr$1 = 0;
+let transformPtr = 0;
+let uniformsPtr = 0;
+const UNIFORMS_BUFFER_SIZE = 256;
+const uniformBuffer = new Float32Array(UNIFORMS_BUFFER_SIZE);
+// =============================================================================
+// Initialization
+// =============================================================================
+function initDrawAPI(wasmModule) {
+ module$4 = wasmModule;
+ viewProjectionPtr$1 = module$4._malloc(16 * 4);
+ transformPtr = module$4._malloc(16 * 4);
+ uniformsPtr = module$4._malloc(UNIFORMS_BUFFER_SIZE * 4);
+}
+function shutdownDrawAPI() {
+ if (module$4) {
+ if (viewProjectionPtr$1) {
+ module$4._free(viewProjectionPtr$1);
+ viewProjectionPtr$1 = 0;
}
- }
- // =========================================================================
- // Public API
- // =========================================================================
- async loadTexture(source) {
- const cached = this.cache_.get(source);
- if (cached) {
- return cached;
+ if (transformPtr) {
+ module$4._free(transformPtr);
+ transformPtr = 0;
}
- const pending = this.pending_.get(source);
- if (pending) {
- return pending;
+ if (uniformsPtr) {
+ module$4._free(uniformsPtr);
+ uniformsPtr = 0;
}
- const promise = this.loadTextureInternal(source);
- this.pending_.set(source, promise);
+ }
+ module$4 = null;
+}
+// =============================================================================
+// Draw Implementation
+// =============================================================================
+function getModule$2() {
+ if (!module$4) {
+ throw new Error('Draw API not initialized. Call initDrawAPI() first.');
+ }
+ return module$4;
+}
+const WHITE = { x: 1, y: 1, z: 1, w: 1 };
+const Draw = {
+ begin(viewProjection) {
+ const m = getModule$2();
+ m.HEAPF32.set(viewProjection, viewProjectionPtr$1 / 4);
+ m.draw_begin(viewProjectionPtr$1);
+ },
+ end() {
+ getModule$2().draw_end();
+ },
+ line(from, to, color, thickness = 1) {
+ getModule$2().draw_line(from.x, from.y, to.x, to.y, color.x, color.y, color.z, color.w, thickness);
+ },
+ rect(position, size, color, filled = true) {
+ getModule$2().draw_rect(position.x, position.y, size.x, size.y, color.x, color.y, color.z, color.w, filled);
+ },
+ rectOutline(position, size, color, thickness = 1) {
+ getModule$2().draw_rectOutline(position.x, position.y, size.x, size.y, color.x, color.y, color.z, color.w, thickness);
+ },
+ circle(center, radius, color, filled = true, segments = 32) {
+ getModule$2().draw_circle(center.x, center.y, radius, color.x, color.y, color.z, color.w, filled, segments);
+ },
+ circleOutline(center, radius, color, thickness = 1, segments = 32) {
+ getModule$2().draw_circleOutline(center.x, center.y, radius, color.x, color.y, color.z, color.w, thickness, segments);
+ },
+ texture(position, size, textureHandle, tint = WHITE) {
+ getModule$2().draw_texture(position.x, position.y, size.x, size.y, textureHandle, tint.x, tint.y, tint.z, tint.w);
+ },
+ textureRotated(position, size, rotation, textureHandle, tint = WHITE) {
+ getModule$2().draw_textureRotated(position.x, position.y, size.x, size.y, rotation, textureHandle, tint.x, tint.y, tint.z, tint.w);
+ },
+ setLayer(layer) {
+ getModule$2().draw_setLayer(layer);
+ },
+ setDepth(depth) {
+ getModule$2().draw_setDepth(depth);
+ },
+ getDrawCallCount() {
+ if (!module$4)
+ return 0;
+ return module$4.draw_getDrawCallCount();
+ },
+ getPrimitiveCount() {
+ if (!module$4)
+ return 0;
+ return module$4.draw_getPrimitiveCount();
+ },
+ setBlendMode(mode) {
+ getModule$2().draw_setBlendMode(mode);
+ },
+ setDepthTest(enabled) {
+ getModule$2().draw_setDepthTest(enabled);
+ },
+ drawMesh(geometry, shader, transform) {
+ const m = getModule$2();
+ m.HEAPF32.set(transform, transformPtr / 4);
+ m.draw_mesh(geometry, shader, transformPtr);
+ },
+ drawMeshWithMaterial(geometry, material, transform) {
+ const m = getModule$2();
+ const matData = Material.get(material);
+ if (!matData)
+ return;
+ Draw.setBlendMode(matData.blendMode);
+ Draw.setDepthTest(matData.depthTest);
+ if (matData.uniforms.size === 0) {
+ Draw.drawMesh(geometry, matData.shader, transform);
+ return;
+ }
+ m.HEAPF32.set(transform, transformPtr / 4);
+ let idx = 0;
+ for (const [name, value] of matData.uniforms) {
+ const nameId = getUniformNameId(name);
+ if (nameId < 0)
+ continue;
+ if (typeof value === 'number') {
+ uniformBuffer[idx++] = 1;
+ uniformBuffer[idx++] = nameId;
+ uniformBuffer[idx++] = value;
+ }
+ else if (Array.isArray(value)) {
+ uniformBuffer[idx++] = value.length;
+ uniformBuffer[idx++] = nameId;
+ for (let i = 0; i < value.length; i++) {
+ uniformBuffer[idx++] = value[i];
+ }
+ }
+ else if ('w' in value) {
+ uniformBuffer[idx++] = 4;
+ uniformBuffer[idx++] = nameId;
+ uniformBuffer[idx++] = value.x;
+ uniformBuffer[idx++] = value.y;
+ uniformBuffer[idx++] = value.z;
+ uniformBuffer[idx++] = value.w;
+ }
+ else if ('z' in value) {
+ uniformBuffer[idx++] = 3;
+ uniformBuffer[idx++] = nameId;
+ uniformBuffer[idx++] = value.x;
+ uniformBuffer[idx++] = value.y;
+ uniformBuffer[idx++] = value.z;
+ }
+ else {
+ uniformBuffer[idx++] = 2;
+ uniformBuffer[idx++] = nameId;
+ uniformBuffer[idx++] = value.x;
+ uniformBuffer[idx++] = value.y;
+ }
+ if (idx > UNIFORMS_BUFFER_SIZE - 6) {
+ console.warn('Uniform buffer overflow, some uniforms will be ignored');
+ break;
+ }
+ }
+ if (idx === 0) {
+ m.draw_mesh(geometry, matData.shader, transformPtr);
+ return;
+ }
+ m.HEAPF32.set(uniformBuffer.subarray(0, idx), uniformsPtr / 4);
+ m.draw_meshWithUniforms(geometry, matData.shader, transformPtr, uniformsPtr, idx);
+ },
+};
+const UNIFORM_NAME_MAP = {
+ 'u_time': 0,
+ 'u_color': 1,
+ 'u_intensity': 2,
+ 'u_scale': 3,
+ 'u_offset': 4,
+ 'u_param0': 5,
+ 'u_param1': 6,
+ 'u_param2': 7,
+ 'u_param3': 8,
+ 'u_param4': 9,
+ 'u_vec0': 10,
+ 'u_vec1': 11,
+ 'u_vec2': 12,
+ 'u_vec3': 13,
+ 'u_texture0': 14,
+ 'u_texture1': 15,
+ 'u_texture2': 16,
+ 'u_texture3': 17,
+};
+function getUniformNameId(name) {
+ return UNIFORM_NAME_MAP[name] ?? -1;
+}
+
+/**
+ * @file geometry.ts
+ * @brief Geometry API for custom mesh rendering
+ * @details Provides geometry creation and management for custom shapes,
+ * particles, trails, and other procedural meshes.
+ */
+var DataType;
+(function (DataType) {
+ DataType[DataType["Float"] = 1] = "Float";
+ DataType[DataType["Float2"] = 2] = "Float2";
+ DataType[DataType["Float3"] = 3] = "Float3";
+ DataType[DataType["Float4"] = 4] = "Float4";
+ DataType[DataType["Int"] = 5] = "Int";
+ DataType[DataType["Int2"] = 6] = "Int2";
+ DataType[DataType["Int3"] = 7] = "Int3";
+ DataType[DataType["Int4"] = 8] = "Int4";
+})(DataType || (DataType = {}));
+// =============================================================================
+// Internal State
+// =============================================================================
+let module$3 = null;
+let vertexPtr = 0;
+let indexPtr = 0;
+let layoutPtr = 0;
+const VERTEX_BUFFER_SIZE = 64 * 1024;
+const INDEX_BUFFER_SIZE = 16 * 1024;
+const LAYOUT_BUFFER_SIZE = 64;
+// =============================================================================
+// Initialization
+// =============================================================================
+function initGeometryAPI(wasmModule) {
+ module$3 = wasmModule;
+ vertexPtr = module$3._malloc(VERTEX_BUFFER_SIZE * 4);
+ indexPtr = module$3._malloc(INDEX_BUFFER_SIZE * 4);
+ layoutPtr = module$3._malloc(LAYOUT_BUFFER_SIZE * 4);
+}
+function shutdownGeometryAPI() {
+ if (module$3) {
+ if (vertexPtr)
+ module$3._free(vertexPtr);
+ if (indexPtr)
+ module$3._free(indexPtr);
+ if (layoutPtr)
+ module$3._free(layoutPtr);
+ vertexPtr = 0;
+ indexPtr = 0;
+ layoutPtr = 0;
+ }
+ module$3 = null;
+}
+// =============================================================================
+// Geometry API
+// =============================================================================
+function getModule$1() {
+ if (!module$3) {
+ throw new Error('Geometry API not initialized. Call initGeometryAPI() first.');
+ }
+ return module$3;
+}
+const Geometry = {
+ /**
+ * Creates a new geometry with vertices and optional indices.
+ * @param options Geometry creation options
+ * @returns Geometry handle
+ */
+ create(options) {
+ const m = getModule$1();
+ const handle = m.geometry_create();
+ if (handle === 0) {
+ throw new Error('Failed to create geometry');
+ }
+ const vertexCount = options.vertices.length;
+ if (vertexCount * 4 > VERTEX_BUFFER_SIZE * 4) {
+ throw new Error(`Vertex data too large: ${vertexCount} floats (max ${VERTEX_BUFFER_SIZE})`);
+ }
+ m.HEAPF32.set(options.vertices, vertexPtr / 4);
+ const layoutCount = options.layout.length;
+ const layoutArray = new Int32Array(layoutCount);
+ for (let i = 0; i < layoutCount; i++) {
+ layoutArray[i] = options.layout[i].type;
+ }
+ const heap32 = new Int32Array(m.HEAPU8.buffer, layoutPtr, layoutCount);
+ heap32.set(layoutArray);
+ m.geometry_init(handle, vertexPtr, vertexCount, layoutPtr, layoutCount, options.dynamic ?? false);
+ if (options.indices) {
+ const indexCount = options.indices.length;
+ if (indexCount * 4 > INDEX_BUFFER_SIZE * 4) {
+ throw new Error(`Index data too large: ${indexCount} indices (max ${INDEX_BUFFER_SIZE})`);
+ }
+ if (options.indices instanceof Uint16Array) {
+ const heap16 = new Uint16Array(m.HEAPU8.buffer, indexPtr, indexCount);
+ heap16.set(options.indices);
+ m.geometry_setIndices16(handle, indexPtr, indexCount);
+ }
+ else {
+ const heap32 = new Uint32Array(m.HEAPU8.buffer, indexPtr, indexCount);
+ heap32.set(options.indices);
+ m.geometry_setIndices32(handle, indexPtr, indexCount);
+ }
+ }
+ return handle;
+ },
+ /**
+ * Updates vertices of a dynamic geometry.
+ * @param handle Geometry handle
+ * @param vertices New vertex data
+ * @param offset Offset in floats
+ */
+ updateVertices(handle, vertices, offset = 0) {
+ const m = getModule$1();
+ const vertexCount = vertices.length;
+ if (vertexCount * 4 > VERTEX_BUFFER_SIZE * 4) {
+ throw new Error(`Vertex data too large: ${vertexCount} floats (max ${VERTEX_BUFFER_SIZE})`);
+ }
+ m.HEAPF32.set(vertices, vertexPtr / 4);
+ m.geometry_updateVertices(handle, vertexPtr, vertexCount, offset);
+ },
+ /**
+ * Releases a geometry.
+ * @param handle Geometry handle
+ */
+ release(handle) {
+ if (handle > 0) {
+ getModule$1().geometry_release(handle);
+ }
+ },
+ /**
+ * Checks if a geometry handle is valid.
+ * @param handle Geometry handle
+ * @returns True if valid
+ */
+ isValid(handle) {
+ if (!module$3 || handle <= 0)
+ return false;
+ return module$3.geometry_isValid(handle);
+ },
+ // =========================================================================
+ // Helper Functions
+ // =========================================================================
+ /**
+ * Creates a unit quad geometry (1x1, centered at origin).
+ * @returns Geometry handle
+ */
+ createQuad(width = 1, height = 1) {
+ const hw = width / 2;
+ const hh = height / 2;
+ return Geometry.create({
+ vertices: new Float32Array([
+ // x, y, u, v
+ -hw, -hh, 0, 0,
+ hw, -hh, 1, 0,
+ hw, hh, 1, 1,
+ -hw, hh, 0, 1,
+ ]),
+ layout: [
+ { name: 'a_position', type: DataType.Float2 },
+ { name: 'a_texCoord', type: DataType.Float2 },
+ ],
+ indices: new Uint16Array([0, 1, 2, 2, 3, 0]),
+ });
+ },
+ /**
+ * Creates a circle geometry.
+ * @param radius Circle radius
+ * @param segments Number of segments
+ * @returns Geometry handle
+ */
+ createCircle(radius = 1, segments = 32) {
+ const vertices = [];
+ const indices = [];
+ vertices.push(0, 0, 0.5, 0.5);
+ for (let i = 0; i <= segments; i++) {
+ const angle = (i / segments) * Math.PI * 2;
+ const x = Math.cos(angle) * radius;
+ const y = Math.sin(angle) * radius;
+ const u = (Math.cos(angle) + 1) / 2;
+ const v = (Math.sin(angle) + 1) / 2;
+ vertices.push(x, y, u, v);
+ }
+ for (let i = 1; i <= segments; i++) {
+ indices.push(0, i, i + 1);
+ }
+ return Geometry.create({
+ vertices: new Float32Array(vertices),
+ layout: [
+ { name: 'a_position', type: DataType.Float2 },
+ { name: 'a_texCoord', type: DataType.Float2 },
+ ],
+ indices: new Uint16Array(indices),
+ });
+ },
+ /**
+ * Creates a polygon geometry from vertices.
+ * @param points Array of {x, y} points
+ * @returns Geometry handle
+ */
+ createPolygon(points) {
+ if (points.length < 3) {
+ throw new Error('Polygon must have at least 3 points');
+ }
+ let minX = Infinity, minY = Infinity;
+ let maxX = -Infinity, maxY = -Infinity;
+ for (const p of points) {
+ minX = Math.min(minX, p.x);
+ minY = Math.min(minY, p.y);
+ maxX = Math.max(maxX, p.x);
+ maxY = Math.max(maxY, p.y);
+ }
+ const vertices = [];
+ for (const p of points) {
+ const u = (p.x - minX) / (maxX - minX);
+ const v = (p.y - minY) / (maxY - minY);
+ vertices.push(p.x, p.y, u, v);
+ }
+ const indices = [];
+ for (let i = 1; i < points.length - 1; i++) {
+ indices.push(0, i, i + 1);
+ }
+ return Geometry.create({
+ vertices: new Float32Array(vertices),
+ layout: [
+ { name: 'a_position', type: DataType.Float2 },
+ { name: 'a_texCoord', type: DataType.Float2 },
+ ],
+ indices: new Uint16Array(indices),
+ });
+ },
+};
+
+/**
+ * @file postprocess.ts
+ * @brief Post-processing effects API
+ * @details Provides full-screen post-processing effects like blur, vignette, etc.
+ */
+// =============================================================================
+// Internal State
+// =============================================================================
+let module$2 = null;
+// =============================================================================
+// Initialization
+// =============================================================================
+function initPostProcessAPI(wasmModule) {
+ module$2 = wasmModule;
+}
+function shutdownPostProcessAPI() {
+ if (module$2 && PostProcess.isInitialized()) {
+ PostProcess.shutdown();
+ }
+ module$2 = null;
+}
+// =============================================================================
+// PostProcess API
+// =============================================================================
+function getModule() {
+ if (!module$2) {
+ throw new Error('PostProcess API not initialized. Call initPostProcessAPI() first.');
+ }
+ return module$2;
+}
+const PostProcess = {
+ /**
+ * Initializes the post-processing pipeline.
+ * @param width Framebuffer width
+ * @param height Framebuffer height
+ * @returns True on success
+ */
+ init(width, height) {
+ return getModule().postprocess_init(width, height);
+ },
+ /**
+ * Shuts down the post-processing pipeline.
+ */
+ shutdown() {
+ getModule().postprocess_shutdown();
+ },
+ /**
+ * Resizes the framebuffers.
+ * @param width New width
+ * @param height New height
+ */
+ resize(width, height) {
+ getModule().postprocess_resize(width, height);
+ },
+ /**
+ * Adds a post-processing pass.
+ * @param name Unique name for the pass
+ * @param shader Shader handle
+ * @returns Pass index
+ */
+ addPass(name, shader) {
+ return getModule().postprocess_addPass(name, shader);
+ },
+ /**
+ * Removes a pass by name.
+ * @param name Pass name
+ */
+ removePass(name) {
+ getModule().postprocess_removePass(name);
+ },
+ /**
+ * Enables or disables a pass.
+ * @param name Pass name
+ * @param enabled Whether to enable the pass
+ */
+ setEnabled(name, enabled) {
+ getModule().postprocess_setPassEnabled(name, enabled);
+ },
+ /**
+ * Checks if a pass is enabled.
+ * @param name Pass name
+ * @returns True if enabled
+ */
+ isEnabled(name) {
+ return getModule().postprocess_isPassEnabled(name);
+ },
+ /**
+ * Sets a float uniform on a pass.
+ * @param passName Pass name
+ * @param uniform Uniform name
+ * @param value Float value
+ */
+ setUniform(passName, uniform, value) {
+ getModule().postprocess_setUniformFloat(passName, uniform, value);
+ },
+ /**
+ * Sets a vec4 uniform on a pass.
+ * @param passName Pass name
+ * @param uniform Uniform name
+ * @param value Vec4 value
+ */
+ setUniformVec4(passName, uniform, value) {
+ getModule().postprocess_setUniformVec4(passName, uniform, value.x, value.y, value.z, value.w);
+ },
+ /**
+ * Begins rendering to the post-process pipeline.
+ * Call this before rendering your scene.
+ */
+ begin() {
+ getModule().postprocess_begin();
+ },
+ /**
+ * Ends and processes all passes.
+ * Call this after rendering your scene.
+ */
+ end() {
+ getModule().postprocess_end();
+ },
+ /**
+ * Gets the number of passes.
+ */
+ getPassCount() {
+ return getModule().postprocess_getPassCount();
+ },
+ /**
+ * Checks if the pipeline is initialized.
+ */
+ isInitialized() {
+ if (!module$2)
+ return false;
+ return module$2.postprocess_isInitialized();
+ },
+ /**
+ * Sets bypass mode to skip FBO rendering entirely.
+ * When bypassed, begin()/end() become no-ops and scene renders directly to screen.
+ * Use this when no post-processing passes are needed for maximum performance.
+ * @param bypass Whether to bypass the pipeline
+ */
+ setBypass(bypass) {
+ getModule().postprocess_setBypass(bypass);
+ },
+ /**
+ * Checks if bypass mode is enabled.
+ * @returns True if bypassed
+ */
+ isBypassed() {
+ if (!module$2)
+ return true;
+ return module$2.postprocess_isBypassed();
+ },
+ // =========================================================================
+ // Built-in Effects
+ // =========================================================================
+ /**
+ * Creates a blur effect shader.
+ * @returns Shader handle
+ */
+ createBlur() {
+ const fragmentSrc = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform vec2 u_resolution;
+uniform float u_intensity;
+out vec4 fragColor;
+
+void main() {
+ vec2 texelSize = 1.0 / u_resolution;
+ float offset = u_intensity;
+
+ vec4 color = vec4(0.0);
+ color += texture(u_texture, v_texCoord + vec2(-offset, -offset) * texelSize) * 0.0625;
+ color += texture(u_texture, v_texCoord + vec2( 0.0, -offset) * texelSize) * 0.125;
+ color += texture(u_texture, v_texCoord + vec2( offset, -offset) * texelSize) * 0.0625;
+ color += texture(u_texture, v_texCoord + vec2(-offset, 0.0) * texelSize) * 0.125;
+ color += texture(u_texture, v_texCoord) * 0.25;
+ color += texture(u_texture, v_texCoord + vec2( offset, 0.0) * texelSize) * 0.125;
+ color += texture(u_texture, v_texCoord + vec2(-offset, offset) * texelSize) * 0.0625;
+ color += texture(u_texture, v_texCoord + vec2( 0.0, offset) * texelSize) * 0.125;
+ color += texture(u_texture, v_texCoord + vec2( offset, offset) * texelSize) * 0.0625;
+
+ fragColor = color;
+}
+`;
+ return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ },
+ /**
+ * Creates a vignette effect shader.
+ * @returns Shader handle
+ */
+ createVignette() {
+ const fragmentSrc = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform float u_intensity;
+uniform float u_softness;
+out vec4 fragColor;
+
+void main() {
+ vec4 color = texture(u_texture, v_texCoord);
+ vec2 uv = v_texCoord * 2.0 - 1.0;
+ float dist = length(uv);
+ float vignette = smoothstep(u_intensity, u_intensity - u_softness, dist);
+ fragColor = vec4(color.rgb * vignette, color.a);
+}
+`;
+ return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ },
+ /**
+ * Creates a grayscale effect shader.
+ * @returns Shader handle
+ */
+ createGrayscale() {
+ const fragmentSrc = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform float u_intensity;
+out vec4 fragColor;
+
+void main() {
+ vec4 color = texture(u_texture, v_texCoord);
+ float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114));
+ fragColor = vec4(mix(color.rgb, vec3(gray), u_intensity), color.a);
+}
+`;
+ return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ },
+ /**
+ * Creates a chromatic aberration effect shader.
+ * @returns Shader handle
+ */
+ createChromaticAberration() {
+ const fragmentSrc = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+uniform sampler2D u_texture;
+uniform vec2 u_resolution;
+uniform float u_intensity;
+out vec4 fragColor;
+
+void main() {
+ vec2 offset = u_intensity / u_resolution;
+ float r = texture(u_texture, v_texCoord + offset).r;
+ float g = texture(u_texture, v_texCoord).g;
+ float b = texture(u_texture, v_texCoord - offset).b;
+ float a = texture(u_texture, v_texCoord).a;
+ fragColor = vec4(r, g, b, a);
+}
+`;
+ return Material.createShader(POSTPROCESS_VERTEX, fragmentSrc);
+ },
+};
+// =============================================================================
+// Shared Vertex Shader
+// =============================================================================
+const POSTPROCESS_VERTEX = `#version 300 es
+precision highp float;
+
+layout(location = 0) in vec2 a_position;
+layout(location = 1) in vec2 a_texCoord;
+
+out vec2 v_texCoord;
+
+void main() {
+ v_texCoord = a_texCoord;
+ gl_Position = vec4(a_position, 0.0, 1.0);
+}
+`;
+
+var RenderStage;
+(function (RenderStage) {
+ RenderStage[RenderStage["Background"] = 0] = "Background";
+ RenderStage[RenderStage["Opaque"] = 1] = "Opaque";
+ RenderStage[RenderStage["Transparent"] = 2] = "Transparent";
+ RenderStage[RenderStage["Overlay"] = 3] = "Overlay";
+})(RenderStage || (RenderStage = {}));
+let module$1 = null;
+let viewProjectionPtr = 0;
+function initRendererAPI(wasmModule) {
+ module$1 = wasmModule;
+ viewProjectionPtr = module$1._malloc(16 * 4);
+}
+function shutdownRendererAPI() {
+ if (module$1 && viewProjectionPtr) {
+ module$1._free(viewProjectionPtr);
+ viewProjectionPtr = 0;
+ }
+ module$1 = null;
+}
+const Renderer = {
+ init(width, height) {
+ module$1?.renderer_init(width, height);
+ },
+ resize(width, height) {
+ module$1?.renderer_resize(width, height);
+ },
+ begin(viewProjection, target) {
+ if (!module$1 || !viewProjectionPtr)
+ return;
+ module$1.HEAPF32.set(viewProjection, viewProjectionPtr / 4);
+ module$1.renderer_begin(viewProjectionPtr, target ?? 0);
+ },
+ end() {
+ module$1?.renderer_end();
+ },
+ submitSprites(registry) {
+ if (!module$1)
+ return;
+ module$1.renderer_submitSprites(registry._cpp);
+ },
+ submitSpine(registry) {
+ if (!module$1)
+ return;
+ module$1.renderer_submitSpine(registry._cpp);
+ },
+ setStage(stage) {
+ module$1?.renderer_setStage(stage);
+ },
+ createRenderTarget(width, height) {
+ return module$1?.renderer_createTarget(width, height) ?? 0;
+ },
+ releaseRenderTarget(handle) {
+ module$1?.renderer_releaseTarget(handle);
+ },
+ getTargetTexture(handle) {
+ return module$1?.renderer_getTargetTexture(handle) ?? 0;
+ },
+ setClearColor(r, g, b, a) {
+ module$1?.renderer_setClearColor?.(r, g, b, a);
+ },
+ getStats() {
+ if (!module$1) {
+ return { drawCalls: 0, triangles: 0, sprites: 0, spine: 0, meshes: 0, culled: 0 };
+ }
+ return {
+ drawCalls: module$1.renderer_getDrawCalls(),
+ triangles: module$1.renderer_getTriangles(),
+ sprites: module$1.renderer_getSprites(),
+ spine: module$1.renderer_getSpine(),
+ meshes: module$1.renderer_getMeshes(),
+ culled: module$1.renderer_getCulled(),
+ };
+ },
+};
+
+/**
+ * @file customDraw.ts
+ * @brief Custom draw callback registration for the render pipeline
+ */
+const callbacks = new Map();
+function registerDrawCallback(id, fn) {
+ callbacks.set(id, fn);
+}
+function unregisterDrawCallback(id) {
+ callbacks.delete(id);
+}
+function clearDrawCallbacks() {
+ callbacks.clear();
+}
+function getDrawCallbacks() {
+ return callbacks;
+}
+
+/**
+ * @file renderPipeline.ts
+ * @brief Unified render pipeline for runtime and editor
+ */
+class RenderPipeline {
+ render(params) {
+ const { registry, viewProjection, width, height, elapsed } = params;
+ Renderer.resize(width, height);
+ const usePostProcess = PostProcess.isInitialized()
+ && PostProcess.getPassCount() > 0
+ && !PostProcess.isBypassed();
+ if (usePostProcess) {
+ PostProcess.resize(width, height);
+ PostProcess.begin();
+ }
+ Renderer.begin(viewProjection);
+ Renderer.submitSprites(registry);
+ Renderer.submitSpine(registry);
+ Renderer.end();
+ const cbs = getDrawCallbacks();
+ if (cbs.size > 0) {
+ Draw.begin(viewProjection);
+ for (const fn of cbs.values()) {
+ try {
+ fn(elapsed);
+ }
+ catch (e) {
+ console.warn('[CustomDraw]', e);
+ }
+ }
+ Draw.end();
+ }
+ if (usePostProcess) {
+ PostProcess.end();
+ }
+ }
+}
+
+/**
+ * @file app.ts
+ * @brief Application builder and web platform integration
+ */
+// =============================================================================
+// App
+// =============================================================================
+class App {
+ constructor() {
+ this.systems_ = new Map();
+ this.runner_ = null;
+ this.running_ = false;
+ this.lastTime_ = 0;
+ this.module_ = null;
+ this.mainLoop = () => {
+ if (!this.running_) {
+ return;
+ }
+ const now = performance.now();
+ const deltaMs = now - this.lastTime_;
+ this.lastTime_ = now;
+ const delta = deltaMs / 1000;
+ this.updateTime(delta);
+ this.runSchedule(Schedule.First);
+ this.runSchedule(Schedule.PreUpdate);
+ this.runSchedule(Schedule.Update);
+ this.runSchedule(Schedule.PostUpdate);
+ this.runSchedule(Schedule.Last);
+ requestAnimationFrame(this.mainLoop);
+ };
+ this.world_ = new World();
+ this.resources_ = new ResourceStorage();
+ for (const s of Object.values(Schedule)) {
+ if (typeof s === 'number') {
+ this.systems_.set(s, []);
+ }
+ }
+ }
+ static new() {
+ return new App();
+ }
+ // =========================================================================
+ // Plugins
+ // =========================================================================
+ addPlugin(plugin) {
+ plugin.build(this);
+ return this;
+ }
+ // =========================================================================
+ // Systems
+ // =========================================================================
+ addSystemToSchedule(schedule, system) {
+ this.systems_.get(schedule).push({ system });
+ return this;
+ }
+ addSystem(system) {
+ return this.addSystemToSchedule(Schedule.Update, system);
+ }
+ addStartupSystem(system) {
+ return this.addSystemToSchedule(Schedule.Startup, system);
+ }
+ // =========================================================================
+ // C++ Integration
+ // =========================================================================
+ connectCpp(cppRegistry, module) {
+ this.world_.connectCpp(cppRegistry);
+ if (module) {
+ this.module_ = module;
+ }
+ return this;
+ }
+ get wasmModule() {
+ return this.module_;
+ }
+ // =========================================================================
+ // World Access
+ // =========================================================================
+ get world() {
+ return this.world_;
+ }
+ // =========================================================================
+ // Resource Access
+ // =========================================================================
+ insertResource(resource, value) {
+ this.resources_.insert(resource, value);
+ return this;
+ }
+ getResource(resource) {
+ return this.resources_.get(resource);
+ }
+ hasResource(resource) {
+ return this.resources_.has(resource);
+ }
+ // =========================================================================
+ // Run
+ // =========================================================================
+ run() {
+ if (this.running_) {
+ return;
+ }
+ this.running_ = true;
+ this.runner_ = new SystemRunner(this.world_, this.resources_);
+ this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0 });
+ this.runSchedule(Schedule.Startup);
+ this.lastTime_ = performance.now();
+ this.mainLoop();
+ }
+ quit() {
+ this.running_ = false;
+ shutdownRendererAPI();
+ shutdownPostProcessAPI();
+ shutdownGeometryAPI();
+ shutdownMaterialAPI();
+ shutdownDrawAPI();
+ }
+ // =========================================================================
+ // Internal
+ // =========================================================================
+ runSchedule(schedule) {
+ const systems = this.systems_.get(schedule);
+ if (!systems || !this.runner_) {
+ return;
+ }
+ for (const entry of systems) {
+ this.runner_.run(entry.system);
+ }
+ }
+ updateTime(delta) {
+ const time = this.resources_.get(Time);
+ const newTime = {
+ delta,
+ elapsed: time.elapsed + delta,
+ frameCount: time.frameCount + 1
+ };
+ this.resources_.set(Time, newTime);
+ }
+}
+function createWebApp(module, options) {
+ const app = App.new();
+ const cppRegistry = new module.Registry();
+ app.connectCpp(cppRegistry, module);
+ if (options?.glContextHandle) {
+ module.initRendererWithContext(options.glContextHandle);
+ }
+ else {
+ module.initRenderer();
+ }
+ initDrawAPI(module);
+ initMaterialAPI(module);
+ initGeometryAPI(module);
+ initPostProcessAPI(module);
+ initRendererAPI(module);
+ const pipeline = new RenderPipeline();
+ let startTime = performance.now();
+ const getViewportSize = options?.getViewportSize ?? (() => ({
+ width: window.innerWidth * (window.devicePixelRatio || 1),
+ height: window.innerHeight * (window.devicePixelRatio || 1)
+ }));
+ const renderSystem = {
+ _id: Symbol('RenderSystem'),
+ _name: 'RenderSystem',
+ _params: [],
+ _fn: () => {
+ const { width, height } = getViewportSize();
+ const vp = computeViewProjection(cppRegistry, width, height);
+ const elapsed = (performance.now() - startTime) / 1000;
+ pipeline.render({
+ registry: { _cpp: cppRegistry },
+ viewProjection: vp,
+ width, height, elapsed,
+ });
+ }
+ };
+ app.addSystemToSchedule(Schedule.Last, renderSystem);
+ app.addPlugin(textPlugin);
+ return app;
+}
+// =============================================================================
+// View-Projection Computation
+// =============================================================================
+const IDENTITY = new Float32Array([
+ 1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1,
+]);
+function computeViewProjection(registry, width, height) {
+ const count = registry.entityCount();
+ const scanLimit = count + 1000;
+ for (let e = 0; e < scanLimit; e++) {
+ if (!registry.valid(e) || !registry.hasCamera(e) || !registry.hasLocalTransform(e)) {
+ continue;
+ }
+ const camera = registry.getCamera(e);
+ if (!camera.isActive)
+ continue;
+ const transform = registry.getLocalTransform(e);
+ const aspect = width / height;
+ let projection;
+ if (camera.projectionType === 1) {
+ const halfH = camera.orthoSize;
+ const halfW = halfH * aspect;
+ projection = ortho(-halfW, halfW, -halfH, halfH, camera.nearPlane, camera.farPlane);
+ }
+ else {
+ projection = perspective(camera.fov * Math.PI / 180, aspect, camera.nearPlane, camera.farPlane);
+ }
+ const view = invertTranslation(transform.position.x, transform.position.y, transform.position.z);
+ return multiply(projection, view);
+ }
+ return IDENTITY;
+}
+function ortho(left, right, bottom, top, near, far) {
+ const m = new Float32Array(16);
+ const rl = right - left;
+ const tb = top - bottom;
+ const fn = far - near;
+ m[0] = 2 / rl;
+ m[5] = 2 / tb;
+ m[10] = -2 / fn;
+ m[12] = -(right + left) / rl;
+ m[13] = -(top + bottom) / tb;
+ m[14] = -(far + near) / fn;
+ m[15] = 1;
+ return m;
+}
+function perspective(fovRad, aspect, near, far) {
+ const m = new Float32Array(16);
+ const f = 1.0 / Math.tan(fovRad / 2);
+ const nf = near - far;
+ m[0] = f / aspect;
+ m[5] = f;
+ m[10] = (far + near) / nf;
+ m[11] = -1;
+ m[14] = (2 * far * near) / nf;
+ return m;
+}
+function invertTranslation(x, y, z) {
+ const m = new Float32Array(16);
+ m[0] = 1;
+ m[5] = 1;
+ m[10] = 1;
+ m[15] = 1;
+ m[12] = -x;
+ m[13] = -y;
+ m[14] = -z;
+ return m;
+}
+function multiply(a, b) {
+ const m = new Float32Array(16);
+ for (let i = 0; i < 4; i++) {
+ for (let j = 0; j < 4; j++) {
+ m[j * 4 + i] =
+ a[0 * 4 + i] * b[j * 4 + 0] +
+ a[1 * 4 + i] * b[j * 4 + 1] +
+ a[2 * 4 + i] * b[j * 4 + 2] +
+ a[3 * 4 + i] * b[j * 4 + 3];
+ }
+ }
+ return m;
+}
+
+/**
+ * @file MaterialLoader.ts
+ * @brief Material asset loading and caching
+ */
+// =============================================================================
+// MaterialLoader
+// =============================================================================
+class MaterialLoader {
+ constructor(shaderLoader, basePath = '') {
+ this.cache_ = new Map();
+ this.pending_ = new Map();
+ this.shaderLoader_ = shaderLoader;
+ this.basePath_ = basePath;
+ }
+ async load(path) {
+ const cached = this.cache_.get(path);
+ if (cached) {
+ return cached;
+ }
+ const pending = this.pending_.get(path);
+ if (pending) {
+ return pending;
+ }
+ const promise = this.loadInternal(path);
+ this.pending_.set(path, promise);
+ try {
+ const result = await promise;
+ this.cache_.set(path, result);
+ return result;
+ }
+ finally {
+ this.pending_.delete(path);
+ }
+ }
+ get(path) {
+ return this.cache_.get(path);
+ }
+ has(path) {
+ return this.cache_.has(path);
+ }
+ release(path) {
+ const loaded = this.cache_.get(path);
+ if (loaded) {
+ Material.release(loaded.handle);
+ this.cache_.delete(path);
+ }
+ }
+ releaseAll() {
+ for (const loaded of this.cache_.values()) {
+ Material.release(loaded.handle);
+ }
+ this.cache_.clear();
+ }
+ async loadInternal(path) {
+ const fullPath = this.resolvePath(path);
+ const exists = await platformFileExists(fullPath);
+ if (!exists) {
+ throw new Error(`Material file not found: ${fullPath}`);
+ }
+ const content = await platformReadTextFile(fullPath);
+ if (!content) {
+ throw new Error(`Failed to read material file: ${fullPath}`);
+ }
+ const data = JSON.parse(content);
+ if (data.type !== 'material') {
+ throw new Error(`Invalid material file type: ${data.type}`);
+ }
+ const shaderPath = this.resolveShaderPath(path, data.shader);
+ const shaderHandle = await this.shaderLoader_.load(shaderPath);
+ const materialHandle = Material.createFromAsset(data, shaderHandle);
+ return {
+ handle: materialHandle,
+ shaderHandle,
+ path,
+ };
+ }
+ resolvePath(path) {
+ if (path.startsWith('/') || path.startsWith('http')) {
+ return path;
+ }
+ return this.basePath_ ? `${this.basePath_}/${path}` : path;
+ }
+ resolveShaderPath(materialPath, shaderPath) {
+ if (shaderPath.startsWith('/') || shaderPath.startsWith('http') || shaderPath.startsWith('assets/')) {
+ return shaderPath;
+ }
+ const dir = materialPath.substring(0, materialPath.lastIndexOf('/'));
+ return dir ? `${dir}/${shaderPath}` : shaderPath;
+ }
+}
+
+/**
+ * @file scene.ts
+ * @brief Scene loading utilities
+ */
+// =============================================================================
+// Scene Loader
+// =============================================================================
+function loadSceneData(world, sceneData) {
+ const entityMap = new Map();
+ for (const entityData of sceneData.entities) {
+ const entity = world.spawn();
+ entityMap.set(entityData.id, entity);
+ for (const compData of entityData.components) {
+ loadComponent(world, entity, compData);
+ }
+ }
+ // Set parent-child relationships
+ for (const entityData of sceneData.entities) {
+ if (entityData.parent !== null) {
+ const entity = entityMap.get(entityData.id);
+ const parentEntity = entityMap.get(entityData.parent);
+ if (entity !== undefined && parentEntity !== undefined) {
+ world.setParent(entity, parentEntity);
+ }
+ }
+ }
+ return entityMap;
+}
+async function loadSceneWithAssets(world, sceneData, options) {
+ const entityMap = new Map();
+ const assetServer = options?.assetServer;
+ const texturePathToUrl = new Map();
+ for (const entityData of sceneData.entities) {
+ const entity = world.spawn();
+ entityMap.set(entityData.id, entity);
+ for (const compData of entityData.components) {
+ if (compData.type === 'Sprite' && assetServer) {
+ const data = compData.data;
+ if (typeof data.texture === 'string' && data.texture) {
+ const texturePath = data.texture;
+ const isDataUrl = texturePath.startsWith('data:');
+ const url = isDataUrl
+ ? texturePath
+ : options?.assetBaseUrl
+ ? `${options.assetBaseUrl}/${texturePath}`
+ : `/${texturePath}`;
+ try {
+ const info = await assetServer.loadTexture(url);
+ data.texture = info.handle;
+ texturePathToUrl.set(texturePath, url);
+ }
+ catch (err) {
+ console.warn(`Failed to load texture: ${url}`, err);
+ data.texture = 0;
+ }
+ }
+ if (typeof data.material === 'string' && data.material) {
+ try {
+ const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);
+ data.material = loaded.handle;
+ }
+ catch (err) {
+ console.warn(`Failed to load material: ${data.material}`, err);
+ data.material = 0;
+ }
+ }
+ }
+ if (compData.type === 'SpineAnimation' && assetServer) {
+ const data = compData.data;
+ const skeletonPath = data.skeletonPath;
+ const atlasPath = data.atlasPath;
+ if (skeletonPath && atlasPath) {
+ const result = await assetServer.loadSpine(skeletonPath, atlasPath, options?.assetBaseUrl);
+ if (!result.success) {
+ console.warn(`Failed to load Spine: ${result.error}`);
+ }
+ }
+ if (typeof data.material === 'string' && data.material) {
+ try {
+ const loaded = await assetServer.loadMaterial(data.material, options?.assetBaseUrl);
+ data.material = loaded.handle;
+ }
+ catch (err) {
+ console.warn(`Failed to load material: ${data.material}`, err);
+ data.material = 0;
+ }
+ }
+ }
+ loadComponent(world, entity, compData);
+ }
+ }
+ for (const entityData of sceneData.entities) {
+ if (entityData.parent !== null) {
+ const entity = entityMap.get(entityData.id);
+ const parentEntity = entityMap.get(entityData.parent);
+ if (entity !== undefined && parentEntity !== undefined) {
+ world.setParent(entity, parentEntity);
+ }
+ }
+ }
+ if (assetServer && sceneData.textureMetadata) {
+ for (const [texturePath, metadata] of Object.entries(sceneData.textureMetadata)) {
+ const url = texturePathToUrl.get(texturePath);
+ if (url && metadata.sliceBorder) {
+ assetServer.setTextureMetadataByPath(url, metadata.sliceBorder);
+ }
+ }
+ }
+ return entityMap;
+}
+function loadComponent(world, entity, compData) {
+ const data = compData.data;
+ switch (compData.type) {
+ case 'LocalTransform':
+ world.insert(entity, LocalTransform, data);
+ break;
+ case 'Sprite':
+ world.insert(entity, Sprite, data);
+ break;
+ case 'Camera':
+ world.insert(entity, Camera, data);
+ break;
+ case 'Canvas':
+ world.insert(entity, Canvas, data);
+ break;
+ case 'Text':
+ world.insert(entity, Text, data);
+ break;
+ case 'SpineAnimation':
+ world.insert(entity, SpineAnimation, data);
+ break;
+ case 'UIRect':
+ world.insert(entity, UIRect, data);
+ break;
+ default:
+ console.warn(`Unknown component type: ${compData.type}`);
+ }
+}
+function updateCameraAspectRatio(world, aspectRatio) {
+ const cameraEntities = world.getEntitiesWithComponents([Camera]);
+ for (const entity of cameraEntities) {
+ const camera = world.get(entity, Camera);
+ if (camera) {
+ camera.aspectRatio = aspectRatio;
+ world.insert(entity, Camera, camera);
+ }
+ }
+}
+
+class AsyncCache {
+ constructor() {
+ this.cache_ = new Map();
+ this.pending_ = new Map();
+ }
+ async getOrLoad(key, loader) {
+ const cached = this.cache_.get(key);
+ if (cached !== undefined) {
+ return cached;
+ }
+ const pending = this.pending_.get(key);
+ if (pending) {
+ return pending;
+ }
+ const promise = loader();
+ this.pending_.set(key, promise);
try {
const result = await promise;
- this.cache_.set(source, result);
+ this.cache_.set(key, result);
return result;
}
finally {
- this.pending_.delete(source);
+ this.pending_.delete(key);
}
}
+ get(key) {
+ return this.cache_.get(key);
+ }
+ has(key) {
+ return this.cache_.has(key);
+ }
+ delete(key) {
+ return this.cache_.delete(key);
+ }
+ clear() {
+ this.cache_.clear();
+ }
+ values() {
+ return this.cache_.values();
+ }
+}
+
+/**
+ * @file AssetServer.ts
+ * @brief Asset loading and caching system
+ */
+// =============================================================================
+// AssetServer
+// =============================================================================
+class AssetServer {
+ constructor(module) {
+ this.textureCache_ = new AsyncCache();
+ this.shaderCache_ = new AsyncCache();
+ this.jsonCache_ = new AsyncCache();
+ this.textCache_ = new AsyncCache();
+ this.binaryCache_ = new AsyncCache();
+ this.loadedSpines_ = new Set();
+ this.virtualFSPaths_ = new Set();
+ this.module_ = module;
+ this.canvas_ = this.createCanvas(512, 512);
+ this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true });
+ const shaderLoader = {
+ load: (path) => this.loadShader(path),
+ get: (path) => this.shaderCache_.get(path),
+ };
+ this.materialLoader_ = new MaterialLoader(shaderLoader);
+ }
+ // =========================================================================
+ // Texture
+ // =========================================================================
+ /**
+ * Load texture with vertical flip (for Sprite/UI).
+ * OpenGL UV origin is bottom-left, so standard images need flipping.
+ */
+ async loadTexture(source) {
+ return this.loadTextureWithFlip(source, true);
+ }
+ /**
+ * Load texture without flip (for Spine).
+ * Spine runtime handles UV coordinates internally.
+ */
+ async loadTextureRaw(source) {
+ return this.loadTextureWithFlip(source, false);
+ }
getTexture(source) {
- return this.cache_.get(source);
+ return this.textureCache_.get(this.textureCacheKey(source, true));
}
hasTexture(source) {
- return this.cache_.has(source);
+ return this.textureCache_.has(this.textureCacheKey(source, true));
}
releaseTexture(source) {
- const info = this.cache_.get(source);
- if (info) {
- const rm = this.module_.getResourceManager();
- rm.releaseTexture(info.handle);
- this.cache_.delete(source);
+ const rm = this.module_.getResourceManager();
+ for (const flip of [true, false]) {
+ const key = this.textureCacheKey(source, flip);
+ const info = this.textureCache_.get(key);
+ if (info) {
+ rm.releaseTexture(info.handle);
+ this.textureCache_.delete(key);
+ }
}
}
releaseAll() {
const rm = this.module_.getResourceManager();
- for (const info of this.cache_.values()) {
+ for (const info of this.textureCache_.values()) {
rm.releaseTexture(info.handle);
}
- this.cache_.clear();
+ this.textureCache_.clear();
+ this.jsonCache_.clear();
+ this.textCache_.clear();
+ this.binaryCache_.clear();
}
setTextureMetadata(handle, border) {
const rm = this.module_.getResourceManager();
rm.setTextureMetadata(handle, border.left, border.right, border.top, border.bottom);
}
setTextureMetadataByPath(source, border) {
- const info = this.cache_.get(source);
+ const info = this.textureCache_.get(this.textureCacheKey(source, true));
if (info) {
this.setTextureMetadata(info.handle, border);
return true;
@@ -1423,11 +3088,163 @@ class AssetServer {
return false;
}
// =========================================================================
- // Private Methods
+ // Spine
+ // =========================================================================
+ async loadSpine(skeletonPath, atlasPath, baseUrl) {
+ const cacheKey = `${skeletonPath}:${atlasPath}`;
+ if (this.loadedSpines_.has(cacheKey)) {
+ return { success: true };
+ }
+ try {
+ const atlasUrl = this.resolveUrl(atlasPath, baseUrl);
+ const atlasResponse = await fetch(atlasUrl);
+ if (!atlasResponse.ok) {
+ return { success: false, error: `Failed to fetch atlas: ${atlasUrl}` };
+ }
+ const atlasContent = await atlasResponse.text();
+ if (!this.writeToVirtualFS(atlasPath, atlasContent)) {
+ return { success: false, error: `Failed to write atlas to virtual FS: ${atlasPath}` };
+ }
+ const atlasDir = atlasPath.substring(0, atlasPath.lastIndexOf('/'));
+ const textureNames = this.parseAtlasTextures(atlasContent);
+ for (const texName of textureNames) {
+ const texPath = atlasDir ? `${atlasDir}/${texName}` : texName;
+ const texUrl = this.resolveUrl(texPath, baseUrl);
+ try {
+ const info = await this.loadTextureRaw(texUrl);
+ const rm = this.module_.getResourceManager();
+ rm.registerTextureWithPath(info.handle, texPath);
+ }
+ catch (err) {
+ console.warn(`[AssetServer] Failed to load Spine texture: ${texPath}`, err);
+ }
+ }
+ const skelUrl = this.resolveUrl(skeletonPath, baseUrl);
+ const skelResponse = await fetch(skelUrl);
+ if (!skelResponse.ok) {
+ return { success: false, error: `Failed to fetch skeleton: ${skelUrl}` };
+ }
+ const isBinary = skeletonPath.endsWith('.skel');
+ const skelData = isBinary
+ ? new Uint8Array(await skelResponse.arrayBuffer())
+ : await skelResponse.text();
+ if (!this.writeToVirtualFS(skeletonPath, skelData)) {
+ return { success: false, error: `Failed to write skeleton to virtual FS: ${skeletonPath}` };
+ }
+ this.loadedSpines_.add(cacheKey);
+ return { success: true };
+ }
+ catch (err) {
+ return { success: false, error: String(err) };
+ }
+ }
+ isSpineLoaded(skeletonPath, atlasPath) {
+ return this.loadedSpines_.has(`${skeletonPath}:${atlasPath}`);
+ }
+ // =========================================================================
+ // Material & Shader
+ // =========================================================================
+ async loadMaterial(path, baseUrl) {
+ return this.materialLoader_.load(this.resolveUrl(path, baseUrl));
+ }
+ getMaterial(path, baseUrl) {
+ return this.materialLoader_.get(this.resolveUrl(path, baseUrl));
+ }
+ hasMaterial(path, baseUrl) {
+ return this.materialLoader_.has(this.resolveUrl(path, baseUrl));
+ }
+ async loadShader(path) {
+ return this.shaderCache_.getOrLoad(path, () => this.loadShaderInternal(path));
+ }
+ // =========================================================================
+ // Generic File Loading
+ // =========================================================================
+ async loadJson(path, options) {
+ const url = this.resolveUrl(path, options?.baseUrl);
+ if (options?.noCache) {
+ return this.fetchJson(url);
+ }
+ return this.jsonCache_.getOrLoad(url, () => this.fetchJson(url));
+ }
+ async loadText(path, options) {
+ const url = this.resolveUrl(path, options?.baseUrl);
+ if (options?.noCache) {
+ return this.fetchText(url);
+ }
+ return this.textCache_.getOrLoad(url, () => this.fetchText(url));
+ }
+ async loadBinary(path, options) {
+ const url = this.resolveUrl(path, options?.baseUrl);
+ if (options?.noCache) {
+ return this.fetchBinary(url);
+ }
+ return this.binaryCache_.getOrLoad(url, () => this.fetchBinary(url));
+ }
+ // =========================================================================
+ // Scene & Batch
+ // =========================================================================
+ async loadScene(world, sceneData) {
+ return loadSceneWithAssets(world, sceneData, { assetServer: this });
+ }
+ async loadAll(manifest) {
+ const bundle = {
+ textures: new Map(),
+ materials: new Map(),
+ spine: new Map(),
+ json: new Map(),
+ text: new Map(),
+ binary: new Map(),
+ };
+ const promises = [];
+ if (manifest.textures) {
+ for (const path of manifest.textures) {
+ promises.push(this.loadTexture(path).then(info => { bundle.textures.set(path, info); }));
+ }
+ }
+ if (manifest.materials) {
+ for (const path of manifest.materials) {
+ promises.push(this.loadMaterial(path).then(mat => { bundle.materials.set(path, mat); }));
+ }
+ }
+ if (manifest.spine) {
+ for (const desc of manifest.spine) {
+ const key = `${desc.skeleton}:${desc.atlas}`;
+ promises.push(this.loadSpine(desc.skeleton, desc.atlas, desc.baseUrl).then(result => {
+ bundle.spine.set(key, result);
+ }));
+ }
+ }
+ if (manifest.json) {
+ for (const path of manifest.json) {
+ promises.push(this.loadJson(path).then(data => { bundle.json.set(path, data); }));
+ }
+ }
+ if (manifest.text) {
+ for (const path of manifest.text) {
+ promises.push(this.loadText(path).then(data => { bundle.text.set(path, data); }));
+ }
+ }
+ if (manifest.binary) {
+ for (const path of manifest.binary) {
+ promises.push(this.loadBinary(path).then(data => { bundle.binary.set(path, data); }));
+ }
+ }
+ await Promise.all(promises);
+ return bundle;
+ }
// =========================================================================
- async loadTextureInternal(source) {
+ // Private - Texture
+ // =========================================================================
+ textureCacheKey(source, flip) {
+ return `${source}:${flip ? 'f' : 'n'}`;
+ }
+ async loadTextureWithFlip(source, flip) {
+ const cacheKey = this.textureCacheKey(source, flip);
+ return this.textureCache_.getOrLoad(cacheKey, () => this.loadTextureInternal(source, flip));
+ }
+ async loadTextureInternal(source, flip) {
const img = await this.loadImage(source);
- return this.createTextureFromImage(img);
+ return this.createTextureFromImage(img, flip);
}
async loadImage(source) {
return new Promise((resolve, reject) => {
@@ -1453,24 +3270,27 @@ class AssetServer {
img.src = source;
});
}
- createTextureFromImage(img) {
+ createTextureFromImage(img, flip) {
const { width, height } = img;
if (this.canvas_.width < width || this.canvas_.height < height) {
this.canvas_.width = Math.max(this.canvas_.width, this.nextPowerOf2(width));
this.canvas_.height = Math.max(this.canvas_.height, this.nextPowerOf2(height));
}
this.ctx_.clearRect(0, 0, this.canvas_.width, this.canvas_.height);
- this.ctx_.globalCompositeOperation = 'copy';
+ this.ctx_.save();
+ if (flip) {
+ this.ctx_.translate(0, height);
+ this.ctx_.scale(1, -1);
+ }
this.ctx_.drawImage(img, 0, 0);
- this.ctx_.globalCompositeOperation = 'source-over';
+ this.ctx_.restore();
const imageData = this.ctx_.getImageData(0, 0, width, height);
const pixels = new Uint8Array(imageData.data.buffer);
this.unpremultiplyAlpha(pixels);
- const flipped = this.flipVertically(pixels, width, height);
const rm = this.module_.getResourceManager();
- const ptr = this.module_._malloc(flipped.length);
- this.module_.HEAPU8.set(flipped, ptr);
- const handle = rm.createTexture(width, height, ptr, flipped.length, 1);
+ const ptr = this.module_._malloc(pixels.length);
+ this.module_.HEAPU8.set(pixels, ptr);
+ const handle = rm.createTexture(width, height, ptr, pixels.length, 1);
this.module_._free(ptr);
return { handle, width, height };
}
@@ -1485,15 +3305,122 @@ class AssetServer {
}
}
}
- flipVertically(pixels, width, height) {
- const rowSize = width * 4;
- const flipped = new Uint8Array(pixels.length);
- for (let y = 0; y < height; y++) {
- const srcOffset = y * rowSize;
- const dstOffset = (height - 1 - y) * rowSize;
- flipped.set(pixels.subarray(srcOffset, srcOffset + rowSize), dstOffset);
+ // =========================================================================
+ // Private - Shader
+ // =========================================================================
+ async loadShaderInternal(path) {
+ const exists = await platformFileExists(path);
+ if (!exists) {
+ throw new Error(`Shader file not found: ${path}`);
}
- return flipped;
+ const content = await platformReadTextFile(path);
+ if (!content) {
+ throw new Error(`Failed to read shader file: ${path}`);
+ }
+ const { vertex, fragment } = this.parseEsShader(content);
+ if (!vertex || !fragment) {
+ throw new Error(`Invalid shader format: ${path}`);
+ }
+ return Material.createShader(vertex, fragment);
+ }
+ parseEsShader(content) {
+ const vertexMatch = content.match(/#pragma\s+vertex\s*([\s\S]*?)#pragma\s+end/);
+ const fragmentMatch = content.match(/#pragma\s+fragment\s*([\s\S]*?)#pragma\s+end/);
+ return {
+ vertex: vertexMatch?.[1].trim() ?? null,
+ fragment: fragmentMatch?.[1].trim() ?? null,
+ };
+ }
+ // =========================================================================
+ // Private - Generic Fetch
+ // =========================================================================
+ async fetchJson(url) {
+ const response = await platformFetch(url);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch JSON: ${url} (${response.status})`);
+ }
+ return response.json();
+ }
+ async fetchText(url) {
+ const response = await platformFetch(url);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch text: ${url} (${response.status})`);
+ }
+ return response.text();
+ }
+ async fetchBinary(url) {
+ const response = await platformFetch(url);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch binary: ${url} (${response.status})`);
+ }
+ return response.arrayBuffer();
+ }
+ // =========================================================================
+ // Private - Virtual FS
+ // =========================================================================
+ writeToVirtualFS(virtualPath, data) {
+ if (this.virtualFSPaths_.has(virtualPath)) {
+ return true;
+ }
+ const fs = this.module_.FS;
+ if (!fs) {
+ return false;
+ }
+ try {
+ this.ensureVirtualDir(virtualPath);
+ fs.writeFile(virtualPath, data);
+ this.virtualFSPaths_.add(virtualPath);
+ return true;
+ }
+ catch (e) {
+ console.error(`[AssetServer] Failed to write to virtual FS: ${virtualPath}`, e);
+ return false;
+ }
+ }
+ ensureVirtualDir(virtualPath) {
+ const fs = this.module_.FS;
+ if (!fs)
+ return;
+ const dir = virtualPath.substring(0, virtualPath.lastIndexOf('/'));
+ if (!dir)
+ return;
+ const parts = dir.split('/').filter(p => p);
+ let currentPath = '';
+ for (const part of parts) {
+ currentPath = currentPath ? `${currentPath}/${part}` : part;
+ try {
+ const analysis = fs.analyzePath(currentPath);
+ if (!analysis.exists) {
+ fs.mkdir(currentPath);
+ }
+ }
+ catch {
+ try {
+ fs.mkdir(currentPath);
+ }
+ catch {
+ // Directory might already exist
+ }
+ }
+ }
+ }
+ // =========================================================================
+ // Private - Utilities
+ // =========================================================================
+ resolveUrl(path, baseUrl) {
+ if (path.startsWith('/') || path.startsWith('http://') || path.startsWith('https://')) {
+ return path;
+ }
+ const base = baseUrl ?? this.baseUrl;
+ return base ? `${base}/${path}` : `/${path}`;
+ }
+ createCanvas(width, height) {
+ const canvas = typeof OffscreenCanvas !== 'undefined'
+ ? new OffscreenCanvas(width, height)
+ : document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ return canvas;
}
nextPowerOf2(n) {
let p = 1;
@@ -1501,13 +3428,24 @@ class AssetServer {
p *= 2;
return p;
}
+ parseAtlasTextures(atlasContent) {
+ const textures = [];
+ for (const line of atlasContent.split('\n')) {
+ const trimmed = line.trim();
+ if (trimmed && !trimmed.includes(':') &&
+ (trimmed.endsWith('.png') || trimmed.endsWith('.jpg'))) {
+ textures.push(trimmed);
+ }
+ }
+ return textures;
+ }
}
/**
* @file AssetPlugin.ts
* @brief Plugin that provides asset loading capabilities
*/
-const Assets = defineResource({ server: null }, 'Assets');
+const Assets = defineResource(null, 'Assets');
// =============================================================================
// Asset Plugin
// =============================================================================
@@ -1518,124 +3456,11 @@ class AssetPlugin {
console.warn('AssetPlugin: No WASM module available');
return;
}
- const server = new AssetServer(module);
- app.insertResource(Assets, { server });
+ app.insertResource(Assets, new AssetServer(module));
}
}
const assetPlugin = new AssetPlugin();
-/**
- * @file scene.ts
- * @brief Scene loading utilities
- */
-// =============================================================================
-// Scene Loader
-// =============================================================================
-function loadSceneData(world, sceneData) {
- const entityMap = new Map();
- for (const entityData of sceneData.entities) {
- const entity = world.spawn();
- entityMap.set(entityData.id, entity);
- for (const compData of entityData.components) {
- loadComponent(world, entity, compData);
- }
- }
- // Set parent-child relationships
- for (const entityData of sceneData.entities) {
- if (entityData.parent !== null) {
- const entity = entityMap.get(entityData.id);
- const parentEntity = entityMap.get(entityData.parent);
- if (entity !== undefined && parentEntity !== undefined) {
- world.setParent(entity, parentEntity);
- }
- }
- }
- return entityMap;
-}
-async function loadSceneWithAssets(world, sceneData, options) {
- const entityMap = new Map();
- const assetServer = options?.assetServer;
- const texturePathToUrl = new Map();
- for (const entityData of sceneData.entities) {
- const entity = world.spawn();
- entityMap.set(entityData.id, entity);
- for (const compData of entityData.components) {
- if (compData.type === 'Sprite' && assetServer) {
- const data = compData.data;
- if (typeof data.texture === 'string' && data.texture) {
- const texturePath = data.texture;
- const isDataUrl = texturePath.startsWith('data:');
- const url = isDataUrl
- ? texturePath
- : options?.assetBaseUrl
- ? `${options.assetBaseUrl}/${texturePath}`
- : `/${texturePath}`;
- try {
- const info = await assetServer.loadTexture(url);
- data.texture = info.handle;
- texturePathToUrl.set(texturePath, url);
- }
- catch (err) {
- console.warn(`Failed to load texture: ${url}`, err);
- data.texture = 0;
- }
- }
- }
- loadComponent(world, entity, compData);
- }
- }
- for (const entityData of sceneData.entities) {
- if (entityData.parent !== null) {
- const entity = entityMap.get(entityData.id);
- const parentEntity = entityMap.get(entityData.parent);
- if (entity !== undefined && parentEntity !== undefined) {
- world.setParent(entity, parentEntity);
- }
- }
- }
- if (assetServer && sceneData.textureMetadata) {
- for (const [texturePath, metadata] of Object.entries(sceneData.textureMetadata)) {
- const url = texturePathToUrl.get(texturePath);
- if (url && metadata.sliceBorder) {
- assetServer.setTextureMetadataByPath(url, metadata.sliceBorder);
- }
- }
- }
- return entityMap;
-}
-function loadComponent(world, entity, compData) {
- const data = compData.data;
- switch (compData.type) {
- case 'LocalTransform':
- world.insert(entity, LocalTransform, data);
- break;
- case 'Sprite':
- world.insert(entity, Sprite, data);
- break;
- case 'Camera':
- world.insert(entity, Camera, data);
- break;
- case 'Canvas':
- world.insert(entity, Canvas, data);
- break;
- case 'Text':
- world.insert(entity, Text, data);
- break;
- default:
- console.warn(`Unknown component type: ${compData.type}`);
- }
-}
-function updateCameraAspectRatio(world, aspectRatio) {
- const cameraEntities = world.getEntitiesWithComponents([Camera]);
- for (const entity of cameraEntities) {
- const camera = world.get(entity, Camera);
- if (camera) {
- camera.aspectRatio = aspectRatio;
- world.insert(entity, Camera, camera);
- }
- }
-}
-
/**
* @file PreviewPlugin.ts
* @brief Plugin for editor preview functionality
@@ -1674,9 +3499,7 @@ class PreviewPlugin {
}
const sceneData = await response.json();
const assets = this.app_.getResource(Assets);
- await loadSceneWithAssets(this.app_.world, sceneData, {
- assetServer: assets.server
- });
+ await assets.loadScene(this.app_.world, sceneData);
this.ensureCamera();
}
catch (err) {
@@ -2022,6 +3845,17 @@ function createSpineController(wasmModule) {
return new SpineController(wasmModule);
}
+let editorMode = false;
+function setEditorMode(active) {
+ editorMode = active;
+}
+function isEditor() {
+ return editorMode;
+}
+function isRuntime() {
+ return !editorMode;
+}
+
/**
* @file index.ts
* @brief ESEngine SDK - Web entry point (auto-initializes Web platform)
@@ -2029,5 +3863,5 @@ function createSpineController(wasmModule) {
// Initialize Web platform
setPlatform(webAdapter);
-export { App, AssetPlugin, AssetServer, Assets, Camera, Canvas, Children, Commands, CommandsInstance, EntityCommands, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Mut, Parent, PreviewPlugin, Query, QueryInstance, Res, ResMut, Schedule, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getPlatform, getPlatformType, isBuiltinComponent, isPlatformInitialized, isWeChat, isWeb, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, textPlugin, updateCameraAspectRatio, vec2, vec3, vec4 };
+export { App, AssetPlugin, AssetServer, Assets, AsyncCache, BlendMode, Camera, Canvas, Children, Commands, CommandsInstance, DataType, Draw, EntityCommands, Geometry, INVALID_ENTITY, INVALID_TEXTURE, Input, LocalTransform, Material, MaterialLoader, Mut, Parent, PostProcess, PreviewPlugin, Query, QueryInstance, RenderPipeline, RenderStage, Renderer, Res, ResMut, Schedule, ShaderSources, SpineAnimation, SpineController, Sprite, SystemRunner, Text, TextAlign, TextOverflow, TextPlugin, TextRenderer, TextVerticalAlign, Time, UIRect, Velocity, World, WorldTransform, assetPlugin, clearDrawCallbacks, color, createSpineController, createWebApp, defineComponent, defineResource, defineSystem, defineTag, getComponentDefaults, getPlatform, getPlatformType, initDrawAPI, initGeometryAPI, initMaterialAPI, initPostProcessAPI, initRendererAPI, isBuiltinComponent, isEditor, isPlatformInitialized, isRuntime, isWeChat, isWeb, loadComponent, loadSceneData, loadSceneWithAssets, platformFetch, platformFileExists, platformInstantiateWasm, platformReadFile, platformReadTextFile, quat, registerDrawCallback, registerMaterialCallback, setEditorMode, shutdownDrawAPI, shutdownGeometryAPI, shutdownMaterialAPI, shutdownPostProcessAPI, shutdownRendererAPI, textPlugin, unregisterDrawCallback, updateCameraAspectRatio, vec2, vec3, vec4 };
//# sourceMappingURL=index.js.map
diff --git a/desktop/public/sdk/esm/wasm.d.ts b/desktop/public/sdk/esm/wasm.d.ts
index 6d66ace74..616ad937d 100644
--- a/desktop/public/sdk/esm/wasm.d.ts
+++ b/desktop/public/sdk/esm/wasm.d.ts
@@ -165,6 +165,7 @@ interface ESEngineModule {
renderer_getSpine(): number;
renderer_getMeshes(): number;
renderer_getCulled(): number;
+ renderer_setClearColor(r: number, g: number, b: number, a: number): void;
_malloc(size: number): number;
_free(ptr: number): void;
}
diff --git a/editor/src/Editor.ts b/editor/src/Editor.ts
index 939b4ca44..ddbd96f25 100644
--- a/editor/src/Editor.ts
+++ b/editor/src/Editor.ts
@@ -4,6 +4,11 @@
*/
import type { App, Entity } from 'esengine';
+import {
+ Draw, Geometry, Material, BlendMode, DataType, ShaderSources,
+ PostProcess, Renderer, RenderStage,
+ registerDrawCallback, unregisterDrawCallback, clearDrawCallbacks,
+} from 'esengine';
import { EditorStore } from './store/EditorStore';
import { EditorBridge } from './bridge/EditorBridge';
import type { PanelInstance, PanelPosition } from './panels/PanelRegistry';
@@ -342,6 +347,18 @@ export class Editor {
showInputDialog,
getEditorInstance,
getEditorStore,
+ Draw,
+ Geometry,
+ Material,
+ BlendMode,
+ DataType,
+ ShaderSources,
+ PostProcess,
+ Renderer,
+ RenderStage,
+ registerDrawCallback,
+ unregisterDrawCallback,
+ clearDrawCallbacks,
};
}
diff --git a/editor/src/renderer/EditorSceneRenderer.ts b/editor/src/renderer/EditorSceneRenderer.ts
index 06a706629..edb2c32ba 100644
--- a/editor/src/renderer/EditorSceneRenderer.ts
+++ b/editor/src/renderer/EditorSceneRenderer.ts
@@ -4,7 +4,20 @@
*/
import type { ESEngineModule } from 'esengine';
-import { initMaterialAPI, shutdownMaterialAPI } from 'esengine';
+import {
+ RenderPipeline,
+ Renderer,
+ initDrawAPI,
+ shutdownDrawAPI,
+ initGeometryAPI,
+ shutdownGeometryAPI,
+ initMaterialAPI,
+ shutdownMaterialAPI,
+ initPostProcessAPI,
+ shutdownPostProcessAPI,
+ initRendererAPI,
+ shutdownRendererAPI,
+} from 'esengine';
import type { SceneData, ComponentData } from '../types/SceneTypes';
import type { EditorStore } from '../store/EditorStore';
import { EditorCamera } from './EditorCamera';
@@ -20,10 +33,12 @@ export class EditorSceneRenderer {
private module_: ESEngineModule | null = null;
private sceneManager_: EditorSceneManager | null = null;
private syncService_: RuntimeSyncService | null = null;
+ private pipeline_: RenderPipeline | null = null;
private camera_: EditorCamera;
private pathResolver_: AssetPathResolver;
private store_: EditorStore | null = null;
private initialized_ = false;
+ private startTime_ = 0;
constructor() {
this.camera_ = new EditorCamera();
@@ -46,7 +61,15 @@ export class EditorSceneRenderer {
return false;
}
+ initDrawAPI(module);
+ initGeometryAPI(module);
initMaterialAPI(module);
+ initPostProcessAPI(module);
+ initRendererAPI(module);
+
+ this.pipeline_ = new RenderPipeline();
+ Renderer.setClearColor(0.1, 0.1, 0.1, 1.0);
+ this.startTime_ = performance.now();
this.sceneManager_ = new EditorSceneManager(module, this.pathResolver_);
this.initialized_ = true;
@@ -121,16 +144,17 @@ export class EditorSceneRenderer {
// =========================================================================
render(width: number, height: number): void {
- if (!this.module_ || !this.sceneManager_ || !this.initialized_) return;
+ if (!this.pipeline_ || !this.sceneManager_ || !this.initialized_) return;
if (width <= 0 || height <= 0) return;
const matrix = this.camera_.getViewProjection(width, height);
- const matrixPtr = this.module_._malloc(64);
- this.module_.HEAPF32.set(matrix, matrixPtr / 4);
-
- this.module_.renderFrameWithMatrix(this.sceneManager_.registry, width, height, matrixPtr);
+ const elapsed = (performance.now() - this.startTime_) / 1000;
- this.module_._free(matrixPtr);
+ this.pipeline_.render({
+ registry: { _cpp: this.sceneManager_.registry },
+ viewProjection: matrix,
+ width, height, elapsed,
+ });
}
// =========================================================================
@@ -149,10 +173,15 @@ export class EditorSceneRenderer {
}
if (this.module_ && this.initialized_) {
+ shutdownDrawAPI();
+ shutdownGeometryAPI();
shutdownMaterialAPI();
+ shutdownPostProcessAPI();
+ shutdownRendererAPI();
this.module_.shutdownRenderer();
}
+ this.pipeline_ = null;
this.initialized_ = false;
this.module_ = null;
}
diff --git a/editor/src/scripting/esbuildPlugins.ts b/editor/src/scripting/esbuildPlugins.ts
index e78530ae6..077ba0925 100644
--- a/editor/src/scripting/esbuildPlugins.ts
+++ b/editor/src/scripting/esbuildPlugins.ts
@@ -55,6 +55,9 @@ const EDITOR_SHIM_EXPORTS = [
'icons', 'showToast', 'showSuccessToast', 'showErrorToast',
'showContextMenu', 'showConfirmDialog', 'showInputDialog',
'getEditorInstance', 'getEditorStore',
+ 'Draw', 'Geometry', 'Material', 'BlendMode', 'DataType', 'ShaderSources',
+ 'PostProcess', 'Renderer', 'RenderStage',
+ 'registerDrawCallback', 'unregisterDrawCallback', 'clearDrawCallbacks',
] as const;
const EDITOR_SHIM_CODE = EDITOR_SHIM_EXPORTS.map(
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index cedcaba96..e6632cdeb 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -13,6 +13,7 @@ import { initMaterialAPI, shutdownMaterialAPI } from './material';
import { initGeometryAPI, shutdownGeometryAPI } from './geometry';
import { initPostProcessAPI, shutdownPostProcessAPI } from './postprocess';
import { initRendererAPI, shutdownRendererAPI } from './renderer';
+import { RenderPipeline } from './renderPipeline';
// =============================================================================
// Plugin Interface
@@ -233,6 +234,9 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A
initPostProcessAPI(module);
initRendererAPI(module);
+ const pipeline = new RenderPipeline();
+ let startTime = performance.now();
+
const getViewportSize = options?.getViewportSize ?? (() => ({
width: window.innerWidth * (window.devicePixelRatio || 1),
height: window.innerHeight * (window.devicePixelRatio || 1)
@@ -244,7 +248,13 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A
_params: [],
_fn: () => {
const { width, height } = getViewportSize();
- module.renderFrame(cppRegistry, width, height);
+ const vp = computeViewProjection(cppRegistry, width, height);
+ const elapsed = (performance.now() - startTime) / 1000;
+ pipeline.render({
+ registry: { _cpp: cppRegistry },
+ viewProjection: vp,
+ width, height, elapsed,
+ });
}
};
@@ -254,3 +264,113 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): A
return app;
}
+
+// =============================================================================
+// View-Projection Computation
+// =============================================================================
+
+const IDENTITY = new Float32Array([
+ 1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1,
+]);
+
+function computeViewProjection(registry: CppRegistry, width: number, height: number): Float32Array {
+ const count = registry.entityCount();
+ const scanLimit = count + 1000;
+
+ for (let e = 0; e < scanLimit; e++) {
+ if (!registry.valid(e) || !registry.hasCamera(e) || !registry.hasLocalTransform(e)) {
+ continue;
+ }
+
+ const camera = registry.getCamera(e) as {
+ projectionType: number;
+ fov: number;
+ orthoSize: number;
+ nearPlane: number;
+ farPlane: number;
+ isActive: boolean;
+ };
+ if (!camera.isActive) continue;
+
+ const transform = registry.getLocalTransform(e) as {
+ position: { x: number; y: number; z: number };
+ };
+
+ const aspect = width / height;
+ let projection: Float32Array;
+
+ if (camera.projectionType === 1) {
+ const halfH = camera.orthoSize;
+ const halfW = halfH * aspect;
+ projection = ortho(-halfW, halfW, -halfH, halfH, camera.nearPlane, camera.farPlane);
+ } else {
+ projection = perspective(
+ camera.fov * Math.PI / 180,
+ aspect,
+ camera.nearPlane,
+ camera.farPlane,
+ );
+ }
+
+ const view = invertTranslation(transform.position.x, transform.position.y, transform.position.z);
+ return multiply(projection, view);
+ }
+
+ return IDENTITY;
+}
+
+function ortho(left: number, right: number, bottom: number, top: number, near: number, far: number): Float32Array {
+ const m = new Float32Array(16);
+ const rl = right - left;
+ const tb = top - bottom;
+ const fn = far - near;
+ m[0] = 2 / rl;
+ m[5] = 2 / tb;
+ m[10] = -2 / fn;
+ m[12] = -(right + left) / rl;
+ m[13] = -(top + bottom) / tb;
+ m[14] = -(far + near) / fn;
+ m[15] = 1;
+ return m;
+}
+
+function perspective(fovRad: number, aspect: number, near: number, far: number): Float32Array {
+ const m = new Float32Array(16);
+ const f = 1.0 / Math.tan(fovRad / 2);
+ const nf = near - far;
+ m[0] = f / aspect;
+ m[5] = f;
+ m[10] = (far + near) / nf;
+ m[11] = -1;
+ m[14] = (2 * far * near) / nf;
+ return m;
+}
+
+function invertTranslation(x: number, y: number, z: number): Float32Array {
+ const m = new Float32Array(16);
+ m[0] = 1;
+ m[5] = 1;
+ m[10] = 1;
+ m[15] = 1;
+ m[12] = -x;
+ m[13] = -y;
+ m[14] = -z;
+ return m;
+}
+
+function multiply(a: Float32Array, b: Float32Array): Float32Array {
+ const m = new Float32Array(16);
+ for (let i = 0; i < 4; i++) {
+ for (let j = 0; j < 4; j++) {
+ m[j * 4 + i] =
+ a[0 * 4 + i] * b[j * 4 + 0] +
+ a[1 * 4 + i] * b[j * 4 + 1] +
+ a[2 * 4 + i] * b[j * 4 + 2] +
+ a[3 * 4 + i] * b[j * 4 + 3];
+ }
+ }
+ return m;
+}
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index b71c6884d..cd5d3d00e 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -302,6 +302,26 @@ export {
type RenderStats,
} from './renderer';
+// =============================================================================
+// Render Pipeline
+// =============================================================================
+
+export {
+ RenderPipeline,
+ type RenderParams,
+} from './renderPipeline';
+
+// =============================================================================
+// Custom Draw Callbacks
+// =============================================================================
+
+export {
+ registerDrawCallback,
+ unregisterDrawCallback,
+ clearDrawCallbacks,
+ type DrawCallback,
+} from './customDraw';
+
// =============================================================================
// Environment
// =============================================================================
diff --git a/sdk/src/customDraw.ts b/sdk/src/customDraw.ts
new file mode 100644
index 000000000..960df436c
--- /dev/null
+++ b/sdk/src/customDraw.ts
@@ -0,0 +1,24 @@
+/**
+ * @file customDraw.ts
+ * @brief Custom draw callback registration for the render pipeline
+ */
+
+export type DrawCallback = (elapsed: number) => void;
+
+const callbacks = new Map<string, DrawCallback>();
+
+export function registerDrawCallback(id: string, fn: DrawCallback): void {
+ callbacks.set(id, fn);
+}
+
+export function unregisterDrawCallback(id: string): void {
+ callbacks.delete(id);
+}
+
+export function clearDrawCallbacks(): void {
+ callbacks.clear();
+}
+
+export function getDrawCallbacks(): ReadonlyMap<string, DrawCallback> {
+ return callbacks;
+}
diff --git a/sdk/src/renderPipeline.ts b/sdk/src/renderPipeline.ts
new file mode 100644
index 000000000..ad980fa06
--- /dev/null
+++ b/sdk/src/renderPipeline.ts
@@ -0,0 +1,57 @@
+/**
+ * @file renderPipeline.ts
+ * @brief Unified render pipeline for runtime and editor
+ */
+
+import type { CppRegistry } from './wasm';
+import { Renderer } from './renderer';
+import { PostProcess } from './postprocess';
+import { Draw } from './draw';
+import { getDrawCallbacks } from './customDraw';
+
+export interface RenderParams {
+ registry: { _cpp: CppRegistry };
+ viewProjection: Float32Array;
+ width: number;
+ height: number;
+ elapsed: number;
+}
+
+export class RenderPipeline {
+ render(params: RenderParams): void {
+ const { registry, viewProjection, width, height, elapsed } = params;
+
+ Renderer.resize(width, height);
+
+ const usePostProcess = PostProcess.isInitialized()
+ && PostProcess.getPassCount() > 0
+ && !PostProcess.isBypassed();
+
+ if (usePostProcess) {
+ PostProcess.resize(width, height);
+ PostProcess.begin();
+ }
+
+ Renderer.begin(viewProjection);
+ Renderer.submitSprites(registry);
+ Renderer.submitSpine(registry);
+ Renderer.end();
+
+ const cbs = getDrawCallbacks();
+ if (cbs.size > 0) {
+ Draw.begin(viewProjection);
+ for (const fn of cbs.values()) {
+ try {
+ fn(elapsed);
+ } catch (e) {
+ console.warn('[CustomDraw]', e);
+ }
+ }
+ Draw.end();
+ }
+
+ if (usePostProcess) {
+ PostProcess.end();
+ }
+ }
+}
diff --git a/sdk/src/renderer.ts b/sdk/src/renderer.ts
index 3a7715a6b..f8b7e40a2 100644
--- a/sdk/src/renderer.ts
+++ b/sdk/src/renderer.ts
@@ -79,6 +79,10 @@ export const Renderer = {
return module?.renderer_getTargetTexture(handle) ?? 0;
},
+ setClearColor(r: number, g: number, b: number, a: number): void {
+ module?.renderer_setClearColor?.(r, g, b, a);
+ },
+
getStats(): RenderStats {
if (!module) {
return { drawCalls: 0, triangles: 0, sprites: 0, spine: 0, meshes: 0, culled: 0 };
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index aa3eaaaaf..c230056c0 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -201,6 +201,7 @@ export interface ESEngineModule {
renderer_getSpine(): number;
renderer_getMeshes(): number;
renderer_getCulled(): number;
+ renderer_setClearColor(r: number, g: number, b: number, a: number): void;
_malloc(size: number): number;
_free(ptr: number): void;
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 22c9f30d8..d55714364 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -53,6 +53,7 @@ static bool g_initialized = false;
static bool g_immediateDrawActive = false;
static u32 g_viewportWidth = 1280;
static u32 g_viewportHeight = 720;
+static glm::vec4 g_clearColor{0.0f, 0.0f, 0.0f, 1.0f};
using GetMaterialCallback = void (*)(u32 materialId, u32* outShaderId, u32* outBlendMode,
u32* outUniformBufferPtr, u32* outUniformCount);
@@ -868,7 +869,7 @@ void renderer_begin(uintptr_t matrixPtr, u32 targetHandle) {
glm::mat4 viewProjection = glm::make_mat4(matrixData);
glViewport(0, 0, g_viewportWidth, g_viewportHeight);
- glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
+ glClearColor(g_clearColor.r, g_clearColor.g, g_clearColor.b, g_clearColor.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_renderFrame->begin(viewProjection, targetHandle);
@@ -942,6 +943,10 @@ u32 renderer_getCulled() {
return g_renderFrame->stats().culled;
}
+void renderer_setClearColor(f32 r, f32 g, f32 b, f32 a) {
+ g_clearColor = glm::vec4(r, g, b, a);
+}
+
} // namespace esengine
EMSCRIPTEN_BINDINGS(esengine_renderer) {
@@ -1033,6 +1038,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderer_getSpine", &esengine::renderer_getSpine);
emscripten::function("renderer_getMeshes", &esengine::renderer_getMeshes);
emscripten::function("renderer_getCulled", &esengine::renderer_getCulled);
+ emscripten::function("renderer_setClearColor", &esengine::renderer_setClearColor);
}
int main() {