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: add material API, asset loader and scene integration to SDK

esengine4c80885e7f27
diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.ts
index 5bfa94efa..7b411366e 100644
--- a/sdk/src/asset/AssetServer.ts
+++ b/sdk/src/asset/AssetServer.ts
@@ -5,6 +5,10 @@
import type { TextureHandle } from '../types';
import type { ESEngineModule } from '../wasm';
+import type { MaterialHandle, ShaderHandle } from '../material';
+import { Material } from '../material';
+import { MaterialLoader, type LoadedMaterial, type ShaderLoader } from './MaterialLoader';
+import { platformReadTextFile, platformFileExists } from '../platform';
// =============================================================================
// Types
@@ -40,6 +44,9 @@ export class AssetServer {
private ctx_: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
private loadedSpines_ = new Map<string, boolean>();
private virtualFSPaths_ = new Set<string>();
+ private materialLoader_: MaterialLoader | null = null;
+ private shaderCache_ = new Map<string, ShaderHandle>();
+ private shaderPending_ = new Map<string, Promise<ShaderHandle>>();
constructor(module: ESEngineModule) {
this.module_ = module;
@@ -53,6 +60,12 @@ export class AssetServer {
this.canvas_.height = 512;
this.ctx_ = this.canvas_.getContext('2d', { willReadFrequently: true })!;
}
+
+ const shaderLoader: ShaderLoader = {
+ load: (path: string) => this.loadShader(path),
+ get: (path: string) => this.shaderCache_.get(path),
+ };
+ this.materialLoader_ = new MaterialLoader(shaderLoader);
}
// =========================================================================
@@ -188,6 +201,88 @@ export class AssetServer {
return this.loadedSpines_.get(`${skeletonPath}:${atlasPath}`) ?? false;
}
+ async loadMaterial(path: string, baseUrl?: string): Promise<LoadedMaterial> {
+ if (!this.materialLoader_) {
+ throw new Error('MaterialLoader not initialized');
+ }
+ const fullPath = this.resolveAssetPath(path, baseUrl);
+ return this.materialLoader_.load(fullPath);
+ }
+
+ getMaterial(path: string, baseUrl?: string): LoadedMaterial | undefined {
+ if (!this.materialLoader_) return undefined;
+ const fullPath = this.resolveAssetPath(path, baseUrl);
+ return this.materialLoader_.get(fullPath);
+ }
+
+ hasMaterial(path: string, baseUrl?: string): boolean {
+ if (!this.materialLoader_) return false;
+ const fullPath = this.resolveAssetPath(path, baseUrl);
+ return this.materialLoader_.has(fullPath);
+ }
+
+ async loadShader(path: string): Promise<ShaderHandle> {
+ const cached = this.shaderCache_.get(path);
+ if (cached) return cached;
+
+ const pending = this.shaderPending_.get(path);
+ if (pending) return pending;
+
+ const promise = this.loadShaderInternal(path);
+ this.shaderPending_.set(path, promise);
+
+ try {
+ const handle = await promise;
+ this.shaderCache_.set(path, handle);
+ return handle;
+ } finally {
+ this.shaderPending_.delete(path);
+ }
+ }
+
+ private async loadShaderInternal(path: string): Promise<ShaderHandle> {
+ const exists = await platformFileExists(path);
+ if (!exists) {
+ throw new Error(`Shader file not found: ${path}`);
+ }
+
+ 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);
+ }
+
+ private parseEsShader(content: string): { vertex: string | null; fragment: string | null } {
+ let vertex: string | null = null;
+ let fragment: string | null = null;
+
+ 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/);
+
+ if (vertexMatch) {
+ vertex = vertexMatch[1].trim();
+ }
+ if (fragmentMatch) {
+ fragment = fragmentMatch[1].trim();
+ }
+
+ return { vertex, fragment };
+ }
+
+ private resolveAssetPath(path: string, baseUrl?: string): string {
+ if (path.startsWith('/') || path.startsWith('http')) {
+ return path;
+ }
+ return baseUrl ? `${baseUrl}/${path}` : `/${path}`;
+ }
+
// =========================================================================
// Private Methods
// =========================================================================
diff --git a/sdk/src/asset/MaterialLoader.ts b/sdk/src/asset/MaterialLoader.ts
new file mode 100644
index 000000000..d9813b444
--- /dev/null
+++ b/sdk/src/asset/MaterialLoader.ts
@@ -0,0 +1,128 @@
+/**
+ * @file MaterialLoader.ts
+ * @brief Material asset loading and caching
+ */
+
+import type { MaterialAssetData, MaterialHandle, ShaderHandle } from '../material';
+import { Material } from '../material';
+import { platformReadTextFile, platformFileExists } from '../platform';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+export interface LoadedMaterial {
+ handle: MaterialHandle;
+ shaderHandle: ShaderHandle;
+ path: string;
+}
+
+export interface ShaderLoader {
+ load(path: string): Promise<ShaderHandle>;
+ get(path: string): ShaderHandle | undefined;
+}
+
+// =============================================================================
+// MaterialLoader
+// =============================================================================
+
+export class MaterialLoader {
+ private cache_ = new Map<string, LoadedMaterial>();
+ private pending_ = new Map<string, Promise<LoadedMaterial>>();
+ private shaderLoader_: ShaderLoader;
+ private basePath_: string;
+
+ constructor(shaderLoader: ShaderLoader, basePath: string = '') {
+ this.shaderLoader_ = shaderLoader;
+ this.basePath_ = basePath;
+ }
+
+ async load(path: string): Promise<LoadedMaterial> {
+ 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: string): LoadedMaterial | undefined {
+ return this.cache_.get(path);
+ }
+
+ has(path: string): boolean {
+ return this.cache_.has(path);
+ }
+
+ release(path: string): void {
+ const loaded = this.cache_.get(path);
+ if (loaded) {
+ Material.release(loaded.handle);
+ this.cache_.delete(path);
+ }
+ }
+
+ releaseAll(): void {
+ for (const loaded of this.cache_.values()) {
+ Material.release(loaded.handle);
+ }
+ this.cache_.clear();
+ }
+
+ private async loadInternal(path: string): Promise<LoadedMaterial> {
+ 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) as MaterialAssetData;
+ 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,
+ };
+ }
+
+ private resolvePath(path: string): string {
+ if (path.startsWith('/') || path.startsWith('http')) {
+ return path;
+ }
+ return this.basePath_ ? `${this.basePath_}/${path}` : path;
+ }
+
+ private resolveShaderPath(materialPath: string, shaderPath: string): string {
+ if (shaderPath.startsWith('/') || shaderPath.startsWith('http') || shaderPath.startsWith('assets/')) {
+ return shaderPath;
+ }
+ const dir = materialPath.substring(0, materialPath.lastIndexOf('/'));
+ return dir ? `${dir}/${shaderPath}` : shaderPath;
+ }
+}
diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.ts
index 01a066daf..d3779ad4f 100644
--- a/sdk/src/asset/index.ts
+++ b/sdk/src/asset/index.ts
@@ -5,3 +5,4 @@
export { AssetServer, type TextureInfo, type SpineLoadResult, type SliceBorder } from './AssetServer';
export { Assets, AssetPlugin, assetPlugin, type AssetsData } from './AssetPlugin';
+export { MaterialLoader, type LoadedMaterial, type ShaderLoader } from './MaterialLoader';
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index 94712b5f2..45f5ce058 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -117,6 +117,7 @@ export interface SpriteData {
layer: number;
flipX: boolean;
flipY: boolean;
+ material: number;
}
export interface CameraData {
@@ -164,6 +165,7 @@ export interface SpineAnimationData {
color: Vec4;
layer: number;
skeletonScale: number;
+ material: number;
}
// =============================================================================
@@ -190,7 +192,8 @@ export const Sprite = defineBuiltin<SpriteData>('Sprite', {
uvScale: { x: 1, y: 1 },
layer: 0,
flipX: false,
- flipY: false
+ flipY: false,
+ material: 0
});
export const Camera = defineBuiltin<CameraData>('Camera', {
@@ -237,7 +240,8 @@ export const SpineAnimation = defineBuiltin<SpineAnimationData>('SpineAnimation'
flipY: false,
color: { x: 1, y: 1, z: 1, w: 1 },
layer: 0,
- skeletonScale: 1.0
+ skeletonScale: 1.0,
+ material: 0
});
// =============================================================================
diff --git a/sdk/src/core.ts b/sdk/src/core.ts
index 8be359934..7fb458ae3 100644
--- a/sdk/src/core.ts
+++ b/sdk/src/core.ts
@@ -167,10 +167,13 @@ export {
Assets,
AssetPlugin,
assetPlugin,
+ MaterialLoader,
type TextureInfo,
type SliceBorder,
type SpineLoadResult,
type AssetsData,
+ type LoadedMaterial,
+ type ShaderLoader,
} from './asset';
// =============================================================================
@@ -249,9 +252,11 @@ export {
ShaderSources,
initMaterialAPI,
shutdownMaterialAPI,
+ registerMaterialCallback,
type ShaderHandle,
type MaterialHandle,
type MaterialOptions,
+ type MaterialAssetData,
type UniformValue,
} from './material';
diff --git a/sdk/src/material.ts b/sdk/src/material.ts
index 6cbc39095..3366c480a 100644
--- a/sdk/src/material.ts
+++ b/sdk/src/material.ts
@@ -26,6 +26,15 @@ export interface MaterialOptions {
depthTest?: boolean;
}
+export interface MaterialAssetData {
+ version: string;
+ type: 'material';
+ shader: string;
+ blendMode: number;
+ depthTest: boolean;
+ properties: Record<string, unknown>;
+}
+
interface MaterialData {
shader: ShaderHandle;
uniforms: Map<string, UniformValue>;
@@ -49,11 +58,17 @@ const materials = new Map<MaterialHandle, MaterialData>();
export function initMaterialAPI(wasmModule: ESEngineModule): void {
module = wasmModule;
resourceManager = wasmModule.getResourceManager();
+ registerMaterialCallback();
}
export function shutdownMaterialAPI(): void {
+ if (uniformBuffer !== 0 && module) {
+ module._free(uniformBuffer);
+ uniformBuffer = 0;
+ }
materials.clear();
nextMaterialId = 1;
+ materialCallbackRegistered = false;
resourceManager = null;
module = null;
}
@@ -207,8 +222,209 @@ export const Material = {
isValid(material: MaterialHandle): boolean {
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: MaterialAssetData, shaderHandle: ShaderHandle): MaterialHandle {
+ const uniforms: Record<string, UniformValue> = {};
+
+ 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 as Record<string, number>;
+ 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 };
+ }
+ }
+ }
+
+ return this.create({
+ shader: shaderHandle,
+ uniforms,
+ blendMode: data.blendMode as 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: MaterialHandle): MaterialHandle {
+ const sourceData = materials.get(source);
+ if (!sourceData) {
+ throw new Error(`Invalid source material: ${source}`);
+ }
+
+ const handle = nextMaterialId++;
+ const data: MaterialData = {
+ shader: sourceData.shader,
+ uniforms: new Map(sourceData.uniforms),
+ blendMode: sourceData.blendMode,
+ depthTest: sourceData.depthTest,
+ };
+
+ 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: MaterialHandle, shaderPath: string): MaterialAssetData | null {
+ const data = materials.get(material);
+ if (!data) return null;
+
+ const properties: Record<string, unknown> = {};
+ 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: MaterialHandle): Map<string, UniformValue> {
+ const data = materials.get(material);
+ return data ? new Map(data.uniforms) : new Map();
+ },
};
+// =============================================================================
+// Material Callback Registration
+// =============================================================================
+
+let materialCallbackRegistered = false;
+let uniformBuffer: number = 0;
+const UNIFORM_BUFFER_SIZE = 4096;
+
+function ensureUniformBuffer(): number {
+ if (uniformBuffer === 0 && module) {
+ uniformBuffer = module._malloc(UNIFORM_BUFFER_SIZE);
+ }
+ return uniformBuffer;
+}
+
+function serializeUniforms(uniforms: Map<string, UniformValue>): { ptr: number; count: number } {
+ const bufferPtr = ensureUniformBuffer();
+ if (bufferPtr === 0 || !module) return { ptr: 0, count: 0 };
+
+ let offset = 0;
+ let count = 0;
+ const heap8 = module.HEAPU8;
+ const heap32 = module.HEAPU32;
+ const heapF32 = module.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++;
+ }
+
+ return { ptr: bufferPtr, count };
+}
+
+export function registerMaterialCallback(): void {
+ if (!module || materialCallbackRegistered) return;
+
+ if (!module.addFunction || !module.setMaterialCallback) {
+ console.warn('[Material] Callback registration not available (requires -sALLOW_TABLE_GROWTH)');
+ return;
+ }
+
+ const callback = (
+ materialId: number,
+ outShaderIdPtr: number,
+ outBlendModePtr: number,
+ outUniformBufferPtr: number,
+ outUniformCountPtr: number
+ ) => {
+ const data = materials.get(materialId);
+ if (!data) {
+ module!.HEAPU32[outShaderIdPtr >> 2] = 0;
+ module!.HEAPU32[outBlendModePtr >> 2] = 0;
+ module!.HEAPU32[outUniformBufferPtr >> 2] = 0;
+ module!.HEAPU32[outUniformCountPtr >> 2] = 0;
+ return;
+ }
+
+ module!.HEAPU32[outShaderIdPtr >> 2] = data.shader;
+ module!.HEAPU32[outBlendModePtr >> 2] = data.blendMode;
+
+ const { ptr, count } = serializeUniforms(data.uniforms);
+ module!.HEAPU32[outUniformBufferPtr >> 2] = ptr;
+ module!.HEAPU32[outUniformCountPtr >> 2] = count;
+ };
+
+ const callbackPtr = module.addFunction(callback, 'viiiii');
+ module.setMaterialCallback(callbackPtr);
+ materialCallbackRegistered = true;
+}
+
// =============================================================================
// Built-in Shader Sources
// =============================================================================
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index 249888654..71ac345ad 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -125,6 +125,18 @@ export async function loadSceneWithAssets(
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) {
@@ -141,6 +153,18 @@ export async function loadSceneWithAssets(
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);
diff --git a/sdk/src/wasm.generated.ts b/sdk/src/wasm.generated.ts
index 509da4d1e..9fdf3bb0f 100644
--- a/sdk/src/wasm.generated.ts
+++ b/sdk/src/wasm.generated.ts
@@ -57,6 +57,7 @@ export interface SpineAnimation {
color: Vec4;
layer: number;
skeletonScale: number;
+ material: number;
}
export interface Sprite {
@@ -68,6 +69,7 @@ export interface Sprite {
layer: number;
flipX: boolean;
flipY: boolean;
+ material: number;
}
export interface Parent {
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 78aad7d23..aa3eaaaaf 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -105,10 +105,14 @@ export interface SpineBounds {
export 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;