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.

42.6 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    material.ts
 * @brief   Material and Shader API for custom rendering
 * @details Provides shader creation and material management for custom visual effects.
 */

import type { EngineApi } from '../ecs/bridge/engineApi';
import type { ESEngineModule } from '../wasm';
import { WasmBridge } from '../wasm/WasmBridge';
import { requireResourceManager } from '../wasm/resourceManager';
import { drawPreview, previewCore } from './assetPreview';
import type { Vec2, Vec3, Vec4 } from '../types';
import { BlendMode } from './blend';
import { reflectEsshader } from './shaderReflect';
import type { AssetLease } from '../asset/AssetLease';
import { disposeAll } from '../util/disposeAll';

export type { Vec2, Vec3, Vec4 } from '../types';

// =============================================================================
// Types
// =============================================================================

export type ShaderHandle = number;
export type MaterialHandle = number;

export interface TextureRef {
    __textureRef: true;
    /** ResourceManager texture handle, resolved to a device texture at draw time. */
    textureId: number;
    slot?: number;
}

export type UniformValue = number | Vec2 | Vec3 | Vec4 | number[] | TextureRef;

export function isTextureRef(v: UniformValue): v is TextureRef {
    return typeof v === 'object' && v !== null && '__textureRef' in v;
}

/**
 * Decompose a non-texture uniform value into an arity (1–4) and packed
 * float values. Shared by the material-registration serializer (in this
 * file) and the per-draw uniform path in draw.ts, which previously had
 * their own parallel branches that drifted in subtle ways.
 *
 * The two serializers apply different *type codes* on top of the arity —
 * material.ts uses 0..3 (float, vec2, vec3, vec4), while draw.ts uses
 * 1..4 plus 10 for texture refs. Those layouts match two distinct WASM
 * APIs (material-reflection vs per-draw uniform binding), so the code
 * offsets stay at each call site; only the arity-and-extract step is
 * centralized here.
 */
export interface UniformArity {
    readonly arity: 1 | 2 | 3 | 4;
    readonly values: readonly [number, number, number, number];
}

export function classifyUniformArity(value: Exclude<UniformValue, TextureRef>): UniformArity {
    if (typeof value === 'number') {
        return { arity: 1, values: [value, 0, 0, 0] };
    }
    if (Array.isArray(value)) {
        const arity = Math.max(1, Math.min(value.length, 4)) as 1 | 2 | 3 | 4;
        return {
            arity,
            values: [value[0] ?? 0, value[1] ?? 0, value[2] ?? 0, value[3] ?? 0],
        };
    }
    if ('w' in value) return { arity: 4, values: [value.x, value.y, value.z, value.w] };
    if ('z' in value) return { arity: 3, values: [value.x, value.y, value.z, 0] };
    return { arity: 2, values: [value.x, value.y, 0, 0] };
}

/** Triangle culling mode; mirrors the engine's CullMode. */
export enum CullMode {
    None = 0,
    Back = 1,
    Front = 2,
}

export interface MaterialOptions {
    shader: ShaderHandle;
    uniforms?: Record<string, UniformValue>;
    blendMode?: BlendMode;
    depthTest?: boolean;
    depthWrite?: boolean;
    cull?: CullMode;
    /** Depth-buffer units toward the eye — the only way to say which of two
     *  COPLANAR surfaces wins (a decal on a wall). 0 leaves it where it is. */
    depthBias?: number;
    /** Enabled static switches (#pragma switch) for the record; the shader permutation is
     *  chosen at compile time (see Material.compileShader). Stored for inspection/serialization. */
    switches?: Record<string, boolean>;
}

/** The `version` a `.esmaterial` this build writes carries, named the way its
 *  sibling formats name theirs. */
export const MATERIAL_FORMAT_VERSION = '1.0';

export interface MaterialAssetData {
    version: string;
    type: 'material';
    shader: string;
    // Render state is optional so an instance can serialize only its overrides; a base
    // material writes all of them. Absent fields fall back to the engine defaults on load.
    blendMode?: number;
    depthTest?: boolean;
    depthWrite?: boolean;
    cull?: number;
    depthBias?: number;
    /**
     * Parent material asset ref — present on a material instance (UE MaterialInstanceConstant).
     * The shader and any non-overridden render state are inherited from the parent; `shader`
     * is then ignored and `properties` carries only the overridden parameters (the diff).
     */
    instanceOf?: string;
    /** Enabled static switches (#pragma switch) — selects the shader permutation at load. */
    switches?: Record<string, boolean>;
    properties: Record<string, unknown>;
}

export interface MaterialData {
    shader: ShaderHandle;
    uniforms: Map<string, UniformValue>;
    blendMode: BlendMode;
    depthTest: boolean;
    depthWrite: boolean;
    cull: CullMode;
    /** Depth-buffer units toward the eye — the only way to say which of two
     *  COPLANAR surfaces wins (a decal on a wall). 0 leaves it where it is. */
    depthBias: number;
    /** Enabled static switches (the shader permutation was chosen for these at compile time). */
    switches: Record<string, boolean>;
    /**
     * Instance parenting (UE MaterialInstanceConstant): when set, this material inherits the
     * parent's shader + render state + params, and only its own diffs are stored — `uniforms`
     * holds just the overridden params, and `overrides` names the overridden render-state
     * fields. Undefined on a base material.
     */
    parent?: MaterialHandle;
    /** The permutation an instance switched to for itself; an instance otherwise draws with its parent's shader. */
    ownShader?: ShaderHandle;
    overrides: Set<string>;
    // Immediate-mode mesh uniform cache (draw.ts): the encoded uniform buffer is rebuilt
    // only when dirty_ (a uniform changed). Distinct from the batch render path's material UBO.
    dirty_: boolean;
    cachedBuffer_: Float32Array | null;
    cachedIdx_: number;
    /** What the engine's store holds for each non-texture uniform of this material, as [arity, x, y, z, w]: what was last SENT, not what the caller's
     *  object says now (a caller may reuse and edit one object), which is what lets a write of the number already there be a no-op. */
    sent_?: Map<string, number[]>;
    /** The whole material has been defined and pushed once, so the engine holds the rest of it and one changed value may go alone. */
    pushed_?: boolean;
}

// =============================================================================
// Internal State
// =============================================================================

/**
 * The material entry points as a core that HAS them answers them. Named, not
 * re-declared: the signatures come from the generated engine surface, so this
 * cannot drift from the C++ (MaterialBindings.hpp) that produced it.
 */
type MaterialCore = Required<Pick<NonNullable<EngineApi>,
    'material_compileEsshader' | 'material_define' | 'material_setUniform'
    | 'material_setTexture' | 'material_undefine'>>;

/** Guarded view of the core: after a wasm abort a call throws instead of reaching
 *  a dead module; a native host's bindings never abort. */
class MaterialBridge extends WasmBridge<NonNullable<EngineApi>> {
    protected readonly label = 'material';
}

const bridge = new MaterialBridge();
let module: MaterialCore | null = null;
let nextMaterialId = 1;
const materials = new Map<MaterialHandle, MaterialData>();
type TextureLease = AssetLease<{ handle: number }>;
const ownedTextures = new Map<MaterialHandle, Map<string, TextureLease>>();
const releaseTextures = (leases: Iterable<TextureLease>): void => disposeAll([...new Set(leases)], lease => lease.release());
function replaceTextureOwnership(handle: MaterialHandle, uniforms: ReadonlyMap<string, UniformValue>, incoming?: ReadonlyMap<string, TextureLease>): () => void {
    const old = ownedTextures.get(handle) ?? new Map<string, TextureLease>();
    const next = new Map(incoming ?? old);
    for (const [name, lease] of next) {
        const value = uniforms.get(name);
        if (!value || !isTextureRef(value) || value.textureId !== lease.value.handle) next.delete(name);
    }
    if (next.size) ownedTextures.set(handle, next); else ownedTextures.delete(handle);
    const keep = new Set(next.values());
    const outgoing = [...old.values(), ...(incoming?.values() ?? [])].filter(lease => !keep.has(lease));
    return () => releaseTextures(outgoing);
}
// Reverse index parent -> instances, so editing a base material re-flushes its instances.
const childrenOf = new Map<MaterialHandle, Set<MaterialHandle>>();
// What each compiled shader DECLARES, by handle. Recorded where the source enters the
// engine (compileShader), so every route to a shader — a `.esmaterial`'s file, a built-in
// template, a compiled material graph, a post-process effect — is covered by one door.
// A shader built from raw GLSL (createShader) declares nothing and gets no entry: no
// vocabulary, no verdict.
const declaredParams = new Map<ShaderHandle, Set<string>>();
/** What a compiled permutation was made from, so a material can ask for the same source under other switches. */
interface ProgramOrigin { features: readonly string[]; declared: ReadonlySet<string>; compile(features: string[]): ShaderHandle }
const programOrigins = new Map<ShaderHandle, ProgramOrigin>();
// One complaint per (shader, param). A uniform driven from a system is written every
// frame, and a warning that repeats 60 times a second is a log nobody can read.
const warnedParams = new Set<string>();

// =============================================================================
// Initialization
// =============================================================================

/**
 * @internal Wired by the engine plugins — not part of the public API.
 * Takes whichever core is present (see ecs/engineApi.ts). A core that compiles
 * materials out answers none of these entry points; the caller checks that before
 * connecting, which is what makes the narrowing here sound.
 */
export function initMaterialAPI(engine: NonNullable<EngineApi>): void {
    bridge.connect(engine);
    module = bridge.module as MaterialCore;
}

export function shutdownMaterialAPI(): void {
    const textures = [...ownedTextures.values()].flatMap(held => [...held.values()]);
    ownedTextures.clear();
    try { releaseTextures(textures); }
    finally {
        materials.clear(); childrenOf.clear(); declaredParams.clear(); programOrigins.clear(); warnedParams.clear();
        nextMaterialId = 1; bridge.disconnect(); module = null;
    }
}

/** The shader a material draws with — its own, or the one it inherits as an instance. */
function shaderOf(handle: MaterialHandle): ShaderHandle | undefined {
    let data = materials.get(handle);
    // Bounded: a cycle in the parent chain would otherwise hang a per-write check.
    const own = data?.ownShader;
    for (let depth = 0; data?.parent !== undefined && depth < 16; depth++) data = materials.get(data.parent);
    return own ?? data?.shader;
}

/**
 * Say so when a param name is not one the shader declares.
 *
 * The engine drops an unknown param without a word — MaterialStore keys the std140 layout
 * by the reflected name, so a value under any other name has nowhere to land. That makes a
 * typo the most expensive kind of mistake here: the call succeeds, the value is stored, and
 * the effect never happens. `Material.setUniform(m, 'u_amount', x)` against a shader whose
 * slider is `u_progress` reads as a broken shader, and spelling is the last thing anyone
 * checks. Naming what the shader DOES declare turns that into a one-line fix.
 */
function warnUndeclared(shader: ShaderHandle | undefined, name: string): void {
    const declared = shader !== undefined ? declaredParams.get(shader) : undefined;
    if (!declared || declared.has(name)) return;
    const key = `${shader}:${name}`;
    if (warnedParams.has(key)) return;
    warnedParams.add(key);
    const known = [...declared].join(', ') || '(none)';
    console.warn(`[material] "${name}" is not a parameter of this shader — the value is ignored. It declares: ${known}`);
}

// Pack the render-state flags the engine store expects: depthTest (bit 0), depthWrite
// (bit 1), CullMode (bits 2-3).
function materialFlags(depthTest: boolean, depthWrite: boolean, cull: CullMode): number {
    return (depthTest ? 0x1 : 0) | (depthWrite ? 0x2 : 0) | ((cull & 0x3) << 2);
}

function registerChild(parent: MaterialHandle, child: MaterialHandle): void {
    let set = childrenOf.get(parent);
    if (!set) { set = new Set(); childrenOf.set(parent, set); }
    set.add(child);
}

function unregisterChild(parent: MaterialHandle, child: MaterialHandle): void {
    childrenOf.get(parent)?.delete(child);
}

// Push one param value into the engine material store: texture refs bind to a sampler unit,
// scalar/vector values pack into the std140 MaterialConstants UBO (both by the offset/unit the
// shader's #pragma param reflection assigns). A no-op engine-side for unknown params.
function pushUniform(handle: MaterialHandle, name: string, value: UniformValue): void {
    if (!module) return;
    if (isTextureRef(value)) {
        module.material_setTexture(handle, name, value.textureId);
        return;
    }
    const { arity, values } = classifyUniformArity(value);
    const data = materials.get(handle);
    if (data) {
        let sent = data.sent_;
        if (!sent) { sent = new Map(); data.sent_ = sent; }
        const held = sent.get(name);
        if (held) { held[0] = arity; held[1] = values[0]; held[2] = values[1]; held[3] = values[2]; held[4] = values[3]; }
        else sent.set(name, [arity, values[0], values[1], values[2], values[3]]);
    }
    module.material_setUniform(handle, name, arity, values[0], values[1], values[2], values[3]);
}

/** Whether the engine already holds exactly this value for the uniform. */
function alreadySent(handle: MaterialHandle, name: string, value: Exclude<UniformValue, TextureRef>): boolean {
    const held = materials.get(handle)?.sent_?.get(name);
    if (!held) return false;
    const { arity, values } = classifyUniformArity(value);
    return held[0] === arity && held[1] === values[0] && held[2] === values[1] && held[3] === values[2] && held[4] === values[3];
}

/** One changed uniform to the engine, for this material and the instances that inherit it (those that override the name keep their own). */
function pushChanged(handle: MaterialHandle, name: string, value: UniformValue): void {
    pushUniform(handle, name, value);
    const data = materials.get(handle);
    if (data) data.dirty_ = true;
    const kids = childrenOf.get(handle);
    if (!kids) return;
    for (const child of kids) {
        if (materials.get(child)?.uniforms.has(name)) continue;
        pushChanged(child, name, value);
    }
}

interface ResolvedMaterial {
    shader: ShaderHandle;
    blendMode: BlendMode;
    depthTest: boolean;
    depthWrite: boolean;
    cull: CullMode;
    depthBias: number;
    uniforms: Map<string, UniformValue>;
}
const NO_UNIFORMS = new Map<string, UniformValue>();

// Flatten an instance chain to its effective material: the parent's values with this
// material's overrides applied (uniforms by key, render state by `overrides`). Defensive
// against a missing parent (e.g. a released base) — falls back to the material's own values.
function resolveMaterial(handle: MaterialHandle, includeUniforms = true): ResolvedMaterial | null {
    const data = materials.get(handle);
    if (!data) return null;
    const parent = data.parent !== undefined ? resolveMaterial(data.parent, includeUniforms) : null;
    if (!parent) {
        return {
            shader: data.shader, blendMode: data.blendMode, depthTest: data.depthTest,
            depthWrite: data.depthWrite, cull: data.cull, depthBias: data.depthBias,
            uniforms: includeUniforms ? new Map(data.uniforms) : NO_UNIFORMS,
        };
    }
    const uniforms = parent.uniforms;  // fresh map from the recursive call
    if (includeUniforms) for (const [k, v] of data.uniforms) uniforms.set(k, v);  // instance overrides win
    return {
        shader: data.ownShader ?? parent.shader,  // instances inherit the shader unless they switched permutation
        blendMode: data.overrides.has('blendMode') ? data.blendMode : parent.blendMode,
        depthTest: data.overrides.has('depthTest') ? data.depthTest : parent.depthTest,
        depthWrite: data.overrides.has('depthWrite') ? data.depthWrite : parent.depthWrite,
        cull: data.overrides.has('cull') ? data.cull : parent.cull,
        depthBias: data.overrides.has('depthBias') ? data.depthBias : parent.depthBias,
        uniforms,
    };
}

// Push a material's flattened state to the engine, then re-flush every instance of it — so a
// base edit propagates to non-overriding children. The single push point for create + edits.
function flushMaterial(handle: MaterialHandle, previous?: ReadonlyMap<MaterialHandle, ResolvedMaterial>): void {
    const resolved = resolveMaterial(handle);
    if (resolved && module) {
        // define preserves existing constants and texture bindings. A deleted value
        // must return to the shader default, including in inheriting descendants.
        const old = previous?.get(handle);
        if (old && [...old.uniforms.keys()].some(name => !resolved.uniforms.has(name))) {
            module.material_undefine(handle);
            materials.get(handle)?.sent_?.clear();
        }
        module.material_define(handle, resolved.shader, resolved.blendMode,
            materialFlags(resolved.depthTest, resolved.depthWrite, resolved.cull),
            resolved.depthBias);
        for (const [name, value] of resolved.uniforms) pushUniform(handle, name, value);
        const pushed = materials.get(handle);
        if (pushed) pushed.pushed_ = true;
    }
    const data = materials.get(handle);
    if (data) data.dirty_ = true;
    const kids = childrenOf.get(handle);
    if (kids) for (const child of kids) flushMaterial(child, previous);
}

// Convert a .esmaterial `properties` map (JSON numbers / colors / vectors) into typed
// UniformValues. Keyed by the value's shape: {r,g,b,a} -> color vec4, {x,y,z,w}/{x,y,z}/{x,y}.
function parseAssetProperties(properties: Record<string, unknown>): Record<string, UniformValue> {
    const uniforms: Record<string, UniformValue> = {};
    for (const [key, value] of Object.entries(properties)) {
        if (typeof value === 'number') {
            uniforms[key] = value;
        } else if (typeof value === 'object' && value !== null) {
            const obj = value as Record<string, number>;
            // Any {r,g,b[,a]} is a color → vec4 (alpha defaults to opaque). Keying on
            // 'a' alone silently dropped an alpha-less {r,g,b}.
            if ('r' in obj) uniforms[key] = { x: obj.r ?? 0, y: obj.g ?? 0, z: obj.b ?? 0, w: obj.a ?? 1 };
            else 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 uniforms;
}

// =============================================================================
// Shader API
// =============================================================================

export 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 {
        return requireResourceManager().createShader(vertexSrc, fragmentSrc);
    },

    /**
     * Releases a shader.
     * @param shader Shader handle to release
     */
    releaseShader(shader: ShaderHandle): void {
        if (shader > 0) {
            declaredParams.delete(shader);
            programOrigins.delete(shader);
            requireResourceManager().releaseShader(shader);
        }
    },

    /**
     * Creates a material with a shader and optional settings.
     * @param options Material creation options
     * @returns Material handle
     */
    create(options: MaterialOptions): MaterialHandle {
        const handle = nextMaterialId++;
        const data: MaterialData = {
            shader: options.shader,
            uniforms: new Map(),
            blendMode: options.blendMode ?? BlendMode.Normal,
            depthTest: options.depthTest ?? false,
            depthWrite: options.depthWrite ?? true,
            cull: options.cull ?? CullMode.None,
            depthBias: options.depthBias ?? 0,
            switches: options.switches ? { ...options.switches } : {},
            overrides: new Set(),
            dirty_: true,
            cachedBuffer_: null,
            cachedIdx_: 0,
        };

        if (options.uniforms) {
            for (const [key, value] of Object.entries(options.uniforms)) {
                warnUndeclared(options.shader, key);
                data.uniforms.set(key, value);
            }
        }

        materials.set(handle, data);
        flushMaterial(handle);
        return handle;
    },

    /**
     * Compiles a `.esshader` material shader through the engine's ShaderParser, which
     * generates the std140 MaterialConstants block from its `#pragma param` declarations and
     * registers the param layout. Use this (not createShader) for materials whose parameters
     * should reach the GPU. Returns a shader handle, or 0 on failure.
     */
    compileShader(esshaderSource: string, features: string[] = []): ShaderHandle {
        const handle = module?.material_compileEsshader(esshaderSource, features.join(',')) ?? 0;
        // The same `#pragma param` lines the engine reflected into the layout, kept on this
        // side so a write to a name that is not among them can be reported (warnUndeclared).
        if (handle > 0) {
            declaredParams.set(handle, new Set(reflectEsshader(esshaderSource).params.map((p) => p.name)));
        }
        return handle;
    },

    /**
     * Every live material whose shader declares `param`: what a value that belongs to the whole scene (the weather's wind) is written to, without
     * asking each sprite which material it wears.
     */
    materialsDeclaring(param: string): MaterialHandle[] {
        const found: MaterialHandle[] = [];
        for (const [handle, data] of materials) {
            if (declaredParams.get(data.shader)?.has(param)) found.push(handle);
        }
        return found;
    },

    /**
     * Record what a compiled permutation was made from: the source's switches and how to compile it under others. The asset loader says so for
     * every shader it compiles, which is what lets `recompile` answer for a material that only holds the handle.
     */
    noteProgram(shader: ShaderHandle, features: readonly string[], esshaderSource: string, compile: (features: string[]) => ShaderHandle): void {
        const declared = new Set<string>();
        for (const m of esshaderSource.matchAll(/^[ \t]*#pragma[ \t]+switch[ \t]+(\w+)/gm)) declared.add(m[1]!);
        programOrigins.set(shader, { features, declared, compile });
    },

    /**
     * Switch a material to the permutation of its own shader source that has `changes` applied: a switch the shader does not declare is left out
     * (a project's macro the effect never branched on), and the material takes the permutation at once, with its parameters and textures
     * carried over. A material that inherits (an instance) switches for itself and leaves its parent as it is. Answers whether the shader changed.
     */
    recompile(material: MaterialHandle, changes: Record<string, boolean>): boolean {
        const data = materials.get(material);
        const current = shaderOf(material);
        const origin = current !== undefined ? programOrigins.get(current) : undefined;
        if (!data || !origin) return false;
        const on = new Set(origin.features);
        for (const [name, value] of Object.entries(changes)) {
            data.switches[name] = value;
            if (value) on.add(name); else on.delete(name);
        }
        const features = [...on].filter(name => origin.declared.has(name)).sort();
        const next = origin.compile(features);
        if (next === current || next <= 0) return false;
        if (data.parent === undefined) data.shader = next; else data.ownShader = next;
        flushMaterial(material);
        return true;
    },

    /** Gets an enabled static switch (false when unset). */
    getSwitch(material: MaterialHandle, name: string): boolean {
        return materials.get(material)?.switches[name] ?? false;
    },

    /** Sets a static switch on the record. The shader permutation is chosen at compile time,
     *  so a change takes effect when the material's shader is next (re)compiled — callers that
     *  need it live recompile the shader with the new switch set. */
    setSwitch(material: MaterialHandle, name: string, on: boolean): void {
        const data = materials.get(material);
        if (data) data.switches[name] = on;
    },

    /**
     * Gets material data by handle.
     * @param material Material handle
     * @returns Material data or undefined
     */
    get(material: MaterialHandle): MaterialData | undefined {
        return materials.get(material);
    },

    /** Effective shader/render state without allocating or cloning uniform maps. */
    getRenderState(material: MaterialHandle): Omit<ResolvedMaterial, 'uniforms'> | null {
        const resolved = resolveMaterial(material, false);
        if (!resolved) return null;
        const { uniforms: _, ...state } = resolved;
        return state;
    },

    /**
     * Replace the complete local parameter/render-state snapshot and flush once.
     * Missing fields restore base defaults or remove an instance override, so
     * future parent edits keep propagating. Shader and parent ownership stay with
     * the asset loader; this operation never re-acquires a different generation.
     * When supplied, textureLeases transfers ownership of the complete edited
     * texture set. Receipts remain held until replacement, Reset or material release.
     */
    applyState(material: MaterialHandle, state: Omit<MaterialOptions, 'shader'>,
               textureLeases?: ReadonlyMap<string, TextureLease>): void {
        const data = materials.get(material);
        if (!data) { if (textureLeases) releaseTextures(textureLeases.values()); return; }
        const previous = new Map<MaterialHandle, ResolvedMaterial>();
        const collect = (handle: MaterialHandle): void => {
            if (previous.has(handle)) return;
            const resolved = resolveMaterial(handle);
            if (resolved) previous.set(handle, resolved);
            for (const child of childrenOf.get(handle) ?? []) collect(child);
        };
        collect(material);
        data.uniforms.clear();
        for (const [name, value] of Object.entries(state.uniforms ?? {})) {
            warnUndeclared(shaderOf(material), name); data.uniforms.set(name, value);
        }
        const releasePrevious = replaceTextureOwnership(material, data.uniforms, textureLeases);
        data.blendMode = state.blendMode ?? BlendMode.Normal;
        data.depthTest = state.depthTest ?? false;
        data.depthWrite = state.depthWrite ?? true;
        data.cull = state.cull ?? CullMode.None;
        data.depthBias = Math.round(state.depthBias ?? 0);
        data.switches = { ...state.switches };
        data.overrides.clear();
        if (data.parent !== undefined) {
            for (const key of ['blendMode', 'depthTest', 'depthWrite', 'cull', 'depthBias'] as const)
                if (state[key] !== undefined) data.overrides.add(key);
        }
        try { flushMaterial(material, previous); }
        finally { releasePrevious(); }
    },

    /**
     * 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 {
        const data = materials.get(material);
        if (data) {
            warnUndeclared(shaderOf(material), name);
            const previous = data.uniforms.get(name);
            const plain = !isTextureRef(value) && !(previous !== undefined && isTextureRef(previous));
            // A value written every frame (a time, a colour, a wave table) is mostly the number the engine already has, and the write is a string
            // crossing into wasm; and when it does change, the engine holds the rest of the material already, so only that value goes. A texture
            // is different (it is leased and counted), and a material not yet pushed has nothing to add to: both take the whole flush.
            if (plain && data.pushed_ && module) {
                // On an instance, the local uniforms map *is* the override set (presence = override).
                data.uniforms.set(name, value);
                if (alreadySent(material, name, value as Exclude<UniformValue, TextureRef>)) return;
                data.dirty_ = true;  // immediate-mode mesh path re-encodes its uniform cache.
                pushChanged(material, name, value);
                return;
            }
            // On an instance, the local uniforms map *is* the override set (presence = override).
            data.uniforms.set(name, value);
            const releasePrevious = replaceTextureOwnership(material, data.uniforms);
            data.dirty_ = true;  // immediate-mode mesh path re-encodes its uniform cache.
            try { flushMaterial(material); } // batch path: re-flatten + push (+ propagate to instances).
            finally { releasePrevious(); }
        }
    },

    /**
     * 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 {
        return resolveMaterial(material)?.uniforms.get(name);
    },

    /**
     * Sets the blend mode for a material.
     * @param material Material handle
     * @param mode Blend mode
     */
    setBlendMode(material: MaterialHandle, mode: BlendMode): void {
        const data = materials.get(material);
        if (data) {
            data.blendMode = mode;
            if (data.parent !== undefined) data.overrides.add('blendMode');
            flushMaterial(material);
        }
    },

    /**
     * Gets the blend mode of a material.
     * @param material Material handle
     * @returns Blend mode
     */
    getBlendMode(material: MaterialHandle): BlendMode {
        return resolveMaterial(material, false)?.blendMode ?? BlendMode.Normal;
    },

    /**
     * Sets depth test enabled for a material.
     * @param material Material handle
     * @param enabled Whether depth test is enabled
     */
    setDepthTest(material: MaterialHandle, enabled: boolean): void {
        const data = materials.get(material);
        if (data) {
            data.depthTest = enabled;
            if (data.parent !== undefined) data.overrides.add('depthTest');
            flushMaterial(material);
        }
    },

    /** Enables/disables depth writes (default on, matching the engine's 2D state). */
    setDepthWrite(material: MaterialHandle, enabled: boolean): void {
        const data = materials.get(material);
        if (data) {
            data.depthWrite = enabled;
            if (data.parent !== undefined) data.overrides.add('depthWrite');
            flushMaterial(material);
        }
    },

    /**
     * How far toward the eye this surface is pushed, in depth-buffer units —
     * what makes a decal win against the wall it is laid on. Negative is toward
     * the eye; 0 leaves the surface where its geometry puts it.
     */
    setDepthBias(material: MaterialHandle, units: number): void {
        const data = materials.get(material);
        if (data) {
            data.depthBias = Math.round(units);
            if (data.parent !== undefined) data.overrides.add('depthBias');
            flushMaterial(material);
        }
    },

    /** Sets the triangle culling mode. */
    setCull(material: MaterialHandle, cull: CullMode): void {
        const data = materials.get(material);
        if (data) {
            data.cull = cull;
            if (data.parent !== undefined) data.overrides.add('cull');
            flushMaterial(material);
        }
    },

    /**
     * Gets the shader handle for a material.
     * @param material Material handle
     * @returns Shader handle
     */
    getShader(material: MaterialHandle): ShaderHandle {
        return resolveMaterial(material, false)?.shader ?? 0;
    },

    /**
     * Releases a material (does not release the shader).
     * @param material Material handle
     */
    release(material: MaterialHandle): void {
        const data = materials.get(material);
        if (data?.parent !== undefined) unregisterChild(data.parent, material);
        childrenOf.delete(material);  // orphaned instances fall back to their own values (resolve is defensive)
        materials.delete(material);
        const textures = ownedTextures.get(material); ownedTextures.delete(material);
        try { module?.material_undefine(material); }
        finally { if (textures) releaseTextures(textures.values()); }
    },

    /**
     * Checks if a material exists.
     * @param material Material handle
     * @returns True if material exists
     */
    isValid(material: MaterialHandle): boolean {
        return materials.has(material);
    },

    /**
     * Render a material offscreen at @p w×@p h and resolve with its pixels, through the real
     * viewport path, lit by one directional light. `shape.mesh` (a loaded mesh handle) draws it on
     * that geometry, seen off-axis and framed; without, a sprite shader samples `shape.texture` on
     * a flat quad. Null if the engine isn't ready or the readback fails.
     */
    async renderPreview(material: MaterialHandle, w: number, h: number,
                        shape: { mesh?: number; texture?: number } = {}): Promise<ImageData | null> {
        const connected = module;
        const m = previewCore(connected);
        const data = materials.get(material);
        if (!m || !data) return null;
        const held: TextureLease[] = [];
        try {
            return await drawPreview(m, () => {
                // IDs can be reused after reconnect. Check both identities at
                // submission time, once the shared readback queue reaches us.
                if (module !== connected || materials.get(material) !== data) return false;
                const seen = new Set<number>(); let handle: number | undefined = material;
                while (handle !== undefined && !seen.has(handle)) {
                    seen.add(handle);
                    for (const lease of ownedTextures.get(handle)?.values() ?? []) {
                        const retained = lease.retain(); if (retained) held.push(retained);
                    }
                    handle = materials.get(handle)?.parent;
                }
                return m.renderer_renderMaterialPreview(material, w, h, shape.mesh ?? 0, shape.texture ?? 0);
            });
        } finally { releaseTextures(held); }
    },

    releaseAll(): void {
        try { disposeAll([...materials.keys()], handle => Material.release(handle)); }
        finally { materials.clear(); childrenOf.clear(); }
    },

    /**
     * Creates a material from asset data. When @p parentHandle is given (the asset's
     * `instanceOf` resolved to a loaded parent), builds a Material Instance carrying only the
     * asset's overrides — `properties` and any present render-state fields. Otherwise builds a
     * base material on @p shaderHandle.
     */
    createFromAsset(data: MaterialAssetData, shaderHandle: ShaderHandle, parentHandle?: MaterialHandle): MaterialHandle {
        const uniforms = parseAssetProperties(data.properties);

        if (parentHandle !== undefined && parentHandle !== 0) {
            const handle = this.createInstance(parentHandle);
            for (const [key, value] of Object.entries(uniforms)) this.setUniform(handle, key, value);
            // Present render-state fields are the instance's overrides (absent = inherited).
            if (data.blendMode !== undefined) this.setBlendMode(handle, data.blendMode as BlendMode);
            if (data.depthTest !== undefined) this.setDepthTest(handle, data.depthTest);
            if (data.depthWrite !== undefined) this.setDepthWrite(handle, data.depthWrite);
            if (data.cull !== undefined) this.setCull(handle, data.cull as CullMode);
            if (data.depthBias !== undefined) this.setDepthBias(handle, data.depthBias);
            return handle;
        }

        return this.create({
            shader: shaderHandle,
            uniforms,
            blendMode: (data.blendMode as BlendMode) ?? BlendMode.Normal,
            depthTest: data.depthTest ?? false,
            depthWrite: data.depthWrite ?? true,
            cull: (data.cull as CullMode) ?? CullMode.None,
            depthBias: data.depthBias ?? 0,
            switches: data.switches,
        });
    },

    /**
     * Creates a material instance (UE MaterialInstanceConstant): it inherits @p source's
     * shader, render state and parameters, and stores only the diffs you later set on it.
     * Editing the parent propagates to every non-overriding instance. Use this for cheap
     * variants ("the same material, but red") instead of duplicating the whole material.
     * @param source Parent material (a base material or another instance)
     * @returns New instance handle
     */
    createInstance(source: MaterialHandle): MaterialHandle {
        const sourceData = materials.get(source);
        if (!sourceData) {
            throw new Error(`Invalid source material: ${source}`);
        }

        const handle = nextMaterialId++;
        const data: MaterialData = {
            // Render-state fields are placeholders (resolve inherits from the parent unless an
            // override is set); `uniforms` holds only this instance's overrides, empty at first.
            shader: sourceData.shader,
            uniforms: new Map(),
            blendMode: sourceData.blendMode,
            depthTest: sourceData.depthTest,
            depthWrite: sourceData.depthWrite,
            cull: sourceData.cull,
            depthBias: sourceData.depthBias,
            switches: {},  // instance inherits the parent's shader permutation (switch override = follow-up)
            parent: source,
            overrides: new Set(),
            dirty_: true,
            cachedBuffer_: null,
            cachedIdx_: 0,
        };

        materials.set(handle, data);
        registerChild(source, handle);
        flushMaterial(handle);
        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, parentPath?: string): MaterialAssetData | null {
        const data = materials.get(material);
        if (!data) return null;

        // An instance serializes as a diff: instanceOf + only its overridden params (the local
        // uniforms map) and overridden render-state. A base writes its full state.
        const isInstance = data.parent !== undefined && parentPath !== undefined;

        const properties: Record<string, unknown> = {};
        const localUniforms = isInstance ? data.uniforms : resolveMaterial(material)?.uniforms ?? data.uniforms;
        for (const [key, value] of localUniforms) properties[key] = value;

        if (isInstance) {
            const asset: MaterialAssetData = {
                version: MATERIAL_FORMAT_VERSION, type: 'material', shader: shaderPath, instanceOf: parentPath, properties,
            };
            if (data.overrides.has('blendMode')) asset.blendMode = data.blendMode;
            if (data.overrides.has('depthTest')) asset.depthTest = data.depthTest;
            if (data.overrides.has('depthWrite')) asset.depthWrite = data.depthWrite;
            if (data.overrides.has('cull')) asset.cull = data.cull;
            if (data.overrides.has('depthBias')) asset.depthBias = data.depthBias;
            return asset;
        }

        const asset: MaterialAssetData = {
            version: MATERIAL_FORMAT_VERSION,
            type: 'material',
            shader: shaderPath,
            blendMode: data.blendMode,
            depthTest: data.depthTest,
            depthWrite: data.depthWrite,
            cull: data.cull,
            depthBias: data.depthBias,
            properties,
        };
        if (Object.keys(data.switches).length > 0) asset.switches = { ...data.switches };
        return asset;
    },

    /**
     * Gets all uniforms from a material.
     * @param material Material handle
     * @returns Map of uniform names to values
     */
    getUniforms(material: MaterialHandle): Map<string, UniformValue> {
        // Resolved (flattened) uniforms — an instance reports inherited + overridden params.
        return resolveMaterial(material)?.uniforms ?? new Map();
    },

    tex(textureId: number, slot?: number): TextureRef {
        return { __textureRef: true, textureId, slot };
    },
};

// =============================================================================
// Built-in Shader Sources
// =============================================================================

/**
 * Built-in ES 3.0 shader sources for SDK custom materials.
 * These use the batch renderer vertex layout (vec3 position + vec4 color + vec2 texCoord)
 * and are NOT duplicates of the .esshader files (which are ES 1.0 with different layouts).
 */
export 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;
}
`,
};