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.

68.1 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    component.ts
 * @brief   Component definition and builtin components
 */

import { Entity, Vec2, Vec3, Color, Quat } from '../types';
import { worldUnitDefaults, BUILTIN_WORLD_UNIT_FIELDS } from './worldUnits';
import { deepClone } from '../util/deepClone';
import { hasOwn, setOwn } from '../util/ownProperties';
import { COMPONENT_META, type AssetFieldMeta, type SkeletalFieldMeta } from './component.generated';
export type { AssetFieldMeta, SkeletalFieldMeta };
// C++-backed component data shapes, generated from the ES_COMPONENT structs (single
// source — a TS field can no longer drift from C++). Re-exported below so the public
// `esengine` import site is unchanged; Camera/ParticleEmitter add TS-only fields by
// extending the generated base.
import type {
    TransformData, SpriteData, ShapeRendererData, LightData, ShadowCaster2DData, DraggableData,
    SortingGroupData, GroupOpacityData, SpriteMaskData, LightProbeVolumeData, OccluderData,
    ReflectionProbeData, PlanarReflectionData,
    CanvasData, VelocityData, ParentData, ChildrenData, SpineAnimationData, DragonBonesAnimationData,
    TilemapLayerData, BitmapTextData, TrailRendererData, ParticleForceFieldData, ParticleColliderData, SpringBoneData, SpringBoneColliderData, BillboardData, ImpostorData,
    CameraData as CameraDataCpp, ParticleEmitterData as ParticleEmitterDataCpp,
    MeshRendererData as MeshRendererDataCpp,
} from './component.generated';
// Builtin enums whose values come from C++ ES_ENUMs — imported from the generated
// module (single source) and re-exported below, so a TS const cannot drift from the
// C++ enum and the editor dropdowns derive from the same values. ScaleMode's
// canonical values come from CanvasScaleMode (only its Cocos-compat aliases
// ShowAll/NoBorder are TS-side).
import { ProjectionType, ClearFlags, EmitterShape, SimulationSpace, SubEmitterTrigger, ForceFieldType, ParticleColliderShape, LightType, CanvasScaleMode, ShapeType, ParticleEasing, ParticleCollisionMode, ParticleCollisionFallback, ParticleRenderMode, ReflectionAxis, ReflectionQuality, ReflectionUpdate, SpriteMaskInteraction, SpriteDrawMode, BillboardMode } from '../wasm/wasm.generated';
import { BlendMode } from '../render/blend';
import { getDefaultContext } from './context';
import type {
    RigidBody2DData, BoxCollider2DData, CircleCollider2DData, CapsuleCollider2DData,
} from '../physics/PhysicsComponents';

// =============================================================================
// Self-Describing Component Types
// =============================================================================

/**
 * An asset a component's data points at, as scene preload discovery reports one.
 * `type` is the loader's kind and `path` the project-relative reference.
 *
 * @public
 */
export interface AssetRef {
    type: string;
    path: string;
}

/**
 * Per-field editor presentation metadata — the engine's UPROPERTY analog. A
 * component declares it once at its definition site; the editor's inspector reads
 * it via {@link getComponentFieldMeta} and renders the matching control, falling
 * back to value-shape inference for any field without metadata. None of this is
 * read by the runtime (which stores raw values); it is purely authoring policy
 * co-located with the component so the inspector and the data never diverge.
 *
 * @public
 */
export interface FieldMeta {
    /** Render as a dropdown of these options; the stored value is the option's int. */
    enum?: ReadonlyArray<{ label: string; value: number }>;
    /**
     * Render as a dropdown whose options are resolved by the editor from a named
     * source (e.g. project sorting layers) — falls back to a plain number when the
     * source yields none, so free-int editing survives a project with no named set.
     */
    enumSource?: string;
    /**
     * Names a registered source of LABELS for the entries of a LIST field: the
     * inspector shows a row per entry under the name that source gives it (a
     * morph weight under its shape's name). The labels come from elsewhere —
     * a mesh's own targets — which is why the field cannot state them itself.
     */
    labelSource?: string;
    /** Render as a bitmask multi-select; each option is a single bit. */
    flags?: ReadonlyArray<{ label: string; value: number }>;
    /** Render as a color-gradient editor (the field value is `{ stops: [...] }`). */
    gradient?: boolean;
    /** Render as a scalar over-life curve editor (the field value is `{ keys: [...] }`). */
    curve?: boolean;
    /** Render as a key→value string map editor (the field value is `Record<string,string>`)
     *  — arbitrary user properties (e.g. a Marker's gameplay data), like Tiled's custom
     *  properties. Value-shape inference can't tell a property map from any other object,
     *  so a field must opt in here. */
    map?: boolean;
    /** Render as a post-process effect stack (the field value is the `effects` array).
     *  The rows, their parameters and their ranges come from the effect registry, so an
     *  effect the engine gains is authorable without touching the editor. */
    effectStack?: boolean;
    /**
     * Render as a bitmask whose bit LABELS are resolved by the editor (e.g. named
     * collision layers from project settings) rather than fixed here. `bits` is the
     * count (default 32); `source` names the editor's label provider.
     */
    bitmask?: { bits?: number; source?: string };
    /** Hard numeric range — clamps both typed entry and drag-scrub. */
    min?: number;
    max?: number;
    /** Scrub/step granularity (per pixel for drag, per arrow for the input). */
    step?: number;
    /** Render the number as a slider; requires a finite {@link min}/{@link max}. */
    slider?: boolean;
    /** Unit shown after the resting value (e.g. '°', 'px', '%'). */
    unit?: string;
    /**
     * This field is a fraction of the named sibling, axis-wise (`Sprite.pivot` of
     * `Sprite.size`), so the editor can offer a pixel view of it. The stored value
     * stays the fraction. Authored `normalized_of=` at the C++ ES_PROPERTY site.
     */
    normalizedOf?: string;
    /**
     * The states of a sibling discriminator this field means anything in — a Spot's
     * cone angles to `type: Spot`. The inspector hides it elsewhere and leaves the
     * stored value alone. Authored `shown_when=<field>:<State>` by NAME at the C++
     * ES_PROPERTY site; the names resolve to stored numbers when this is generated.
     */
    shownWhen?: { field: string; values: ReadonlyArray<number> };
    /** Human label / tooltip overriding the key-derived ones. */
    label?: string;
    tooltip?: string;
    /** Group under a category header; `advanced` tucks the field behind a fold. */
    category?: string;
    advanced?: boolean;
}

/**
 * What a component declares about its fields beyond their default values: which
 * are assets, which the editor may keyframe, which replicate. Optional
 * throughout — a component that says nothing gets the derived defaults.
 *
 * @public
 */
export interface ComponentMetadata {
    /**
     * Fields that are world lengths, speeds or accelerations (a radius, a walk speed, gravity): their defaults are
     * written at the reference 100 units a metre and scale with the project's units per metre (ecs/worldUnits.ts).
     * A value a scene states is never scaled.
     */
    worldUnitFields?: string[];
    assetFields?: AssetFieldMeta[];
    skeletalFields?: SkeletalFieldMeta;
    entityFields?: string[];
    /** Per-field editor presentation policy, keyed by field name. */
    fields?: Record<string, FieldMeta>;
    /** Keyframeable fields (Sequencer tracks); auto-derived from numeric fields if omitted. */
    animatableFields?: string[];
    /**
     * Fields the network replication layer syncs (RC11). Whole-field granularity;
     * omitted = the component never replicates. Builtins author this at the C++
     * ES_PROPERTY site (`replicated`) instead — same single-source rule as fieldMeta.
     */
    replicatedFields?: string[];
    /**
     * Engine-COMPUTED output fields (Transform's world-space fields), authored
     * `readonly` at the C++ ES_PROPERTY site. Never authoring inputs — the editor
     * must not project them into the World (it clobbers the composed value).
     */
    readonlyFields?: string[];
    /**
     * Custom asset discovery for scene preload. Authoritative when present:
     * `assetFields` are NOT walked for discovery (they still drive editor
     * pickers/ref rewrites), so the callback can exclude values that are not
     * asset refs (e.g. code-registered FSM/BT names).
     */
    discoverAssets?: (data: Record<string, unknown>) => AssetRef[];
    /**
     * Runtime-only state that must never persist: a transient component is
     * skipped by {@link serializeScene} (e.g. per-frame pointer/drag/hover state
     * that its driving system rebuilds each frame). Systems still
     * read/write it normally; only scene save omits it.
     *
     * Builtins author this at the C++ `ES_COMPONENT(transient)` site — same
     * single-source rule as fieldMeta.
     */
    transient?: boolean;
    /**
     * The name of the bool field that gates this component's part in an entity's
     * visibility — set it and {@link setEntityVisible}, the editor's eye and scene
     * sleep/wake all reach this component. Omitted = the component draws nothing.
     * Builtins author it at the C++ `ES_COMPONENT(renderable=<field>)` site.
     */
    renderableField?: string;
}

/**
 * Build dropdown options from an enum const, so the labels derive from the same
 * definition the runtime uses (no hand-mirrored value→label drift). `only` curates
 * the member set when an enum carries alias entries that share a value (e.g.
 * ScaleMode); otherwise duplicate values are dropped, keeping the first label.
 */
export function enumOptions(
    obj: Record<string, unknown>,
    only?: readonly string[],
): ReadonlyArray<{ label: string; value: number }> {
    const seen = new Set<number>();
    const out: { label: string; value: number }[] = [];
    for (const [k, v] of Object.entries(obj)) {
        // A TS numeric `enum` also carries reverse (value→name) entries; only the
        // name→number direction is a real option.
        if (typeof v !== 'number') continue;
        if (only ? !only.includes(k) : seen.has(v)) continue;
        seen.add(v);
        out.push({ label: k, value: v });
    }
    return out;
}

// =============================================================================
// Component Definition
// =============================================================================

/**
 * A component type, as {@link defineComponent} returns it. Pass it to queries,
 * `world.get`/`world.insert` and `Commands`; the reflection members below are
 * what the editor and the asset cook read, derived from the metadata given at
 * definition. The underscored members are engine plumbing.
 *
 * @public
 */
export interface ComponentDef<T> {
    /** @internal */
    readonly _id: symbol;
    /** @internal */
    readonly _name: string;
    /** @internal */
    readonly _default: T;
    /** @internal */
    readonly _builtin: false;
    readonly assetFields: readonly AssetFieldMeta[];
    readonly skeletalFields?: SkeletalFieldMeta;
    readonly entityFields: readonly string[];
    readonly colorKeys: readonly string[];
    readonly animatableFields: readonly string[];
    /** Fields the replication layer syncs; empty = never replicates. See {@link ComponentMetadata.replicatedFields}. */
    readonly replicatedFields: readonly string[];
    /** Engine-computed output fields the editor must never write back. See {@link ComponentMetadata.readonlyFields}. */
    readonly readonlyFields: readonly string[];
    readonly fieldMeta: Readonly<Record<string, FieldMeta>>;
    readonly discoverAssets?: (data: Record<string, unknown>) => AssetRef[];
    /** Runtime-only: omitted from scene serialization. See {@link ComponentMetadata.transient}. */
    readonly transient: boolean;
    /** Bool field gating this component's visibility, or null if it draws nothing.
     *  See {@link ComponentMetadata.renderableField}. */
    readonly renderableField: string | null;
    create(data?: Partial<T>): T;
}

/**
 * `defaults` with `data` laid over it, ONE LEVEL INTO plain objects: a whole-object
 * overwrite drops what the data does not carry, so a `{x, y}` written before that
 * field grew a `z` would arrive with no depth. Arrays and nested defaults are
 * copied, not shared — two entities taking the default would write into one array.
 */
export function mergeIntoDefaults<T extends object>(defaults: T, data?: Partial<T>): T {
    const out = { ...defaults } as Record<string, unknown>;
    const src = defaults as Record<string, unknown>;
    for (const k of Object.keys(src)) {
        const v = src[k];
        if (Array.isArray(v)) out[k] = v.slice();
        else if (v !== null && typeof v === 'object') out[k] = { ...(v as object) };
    }
    if (!data) return out as T;
    for (const [k, v] of Object.entries(data as Record<string, unknown>)) {
        if (v === undefined) continue;
        const base = hasOwn(out, k) ? out[k] : undefined;
        const nest = base !== null && typeof base === 'object' && !Array.isArray(base)
            && v !== null && typeof v === 'object' && !Array.isArray(v);
        // The default's nested record was already copied above. Reuse that
        // instance on ordinary patches; __proto__ needs spread's own-data write
        // so it cannot invoke the inherited prototype setter.
        const merged = nest
            ? hasOwn(v as object, '__proto__')
                ? { ...(base as object), ...(v as object) }
                : Object.assign(base as object, v)
            : v;
        setOwn(out, k, merged);
    }
    return out as T;
}

function classifyKeys(obj: object): { flatKeys: string[]; objectKeys: string[]; arrayKeys: string[] } | null {
    const flatKeys: string[] = [];
    const objectKeys: string[] = [];
    const arrayKeys: string[] = [];
    let hasNested = false;
    for (const key of Object.keys(obj)) {
        const val = (obj as Record<string, unknown>)[key];
        if (val !== null && typeof val === 'object') {
            hasNested = true;
            if (Array.isArray(val)) {
                arrayKeys.push(key);
            } else {
                objectKeys.push(key);
            }
        } else {
            flatKeys.push(key);
        }
    }
    return hasNested ? { flatKeys, objectKeys, arrayKeys } : null;
}

// User component identity is interned by name: the same name always maps to the same
// _id symbol, module-globally (like builtins, which are defined once at load). The
// World keys storage/queries/change-tracking by _id, so a stable-by-name id lets a
// re-imported project bundle (hot reload) resolve to the live World's existing
// component storage instead of minting a fresh identity that silently misses every
// existing entity. Component DATA stays isolated per-App at the World/storage layer,
// not at the id, so sharing ids by name across contexts is safe — the same reason
// builtins share one global id across every App.
const componentIdRegistry = new Map<string, symbol>();
function componentId(name: string): symbol {
    let id = componentIdRegistry.get(name);
    if (id === undefined) {
        id = Symbol(`Component_${name}`);
        componentIdRegistry.set(name, id);
    }
    return id;
}

function createComponentDef<T extends object>(
    name: string,
    defaults: T,
    metadata?: ComponentMetadata,
): ComponentDef<T> {
    // TypeScript already refuses the wrong shapes — but a project's declarations
    // are BUNDLED, not type-checked, on the path the editor extracts schemas
    // through. So `defineComponent({ name: 'Piece', fields: {...} })`, the shape
    // this reads like, sails through and stores an OBJECT as the component's
    // name. Nothing notices until something sorts by it, a stack away and a
    // second later, as "e.name.localeCompare is not a function" — naming neither
    // the component nor the call. Say it here, where the mistake is.
    if (typeof name !== 'string' || name === '') {
        const got = name === null ? 'null'
            : Array.isArray(name) ? 'an array'
            : typeof name === 'object' ? `an object with keys ${Object.keys(name as object).join(', ')}`
            : `${typeof name} ${JSON.stringify(name)}`;
        throw new Error(
            `defineComponent takes the NAME first and the defaults second — defineComponent('MyThing', `
            + `{ speed: 100 }) — but was given ${got}. Each field's inspector control comes from the TYPE `
            + 'of its default value, so the second argument is real values (speed: 100), not a description '
            + "of them ({ speed: 'number' }).",
        );
    }
    if (defaults === null || typeof defaults !== 'object') {
        throw new Error(
            `Component "${name}": the second argument is the defaults OBJECT — defineComponent('${name}', `
            + `{ speed: 100 }) — but was given ${defaults === undefined ? 'nothing' : JSON.stringify(defaults)}.`,
        );
    }
    const keyInfo = classifyKeys(defaults);
    const defaultsRec = defaults as Record<string, unknown>;
    for (const f of metadata?.worldUnitFields ?? []) {
        if (!hasOwn(defaultsRec, f)) throw new Error(`Component "${name}": worldUnitFields names unknown field "${f}"`);
    }
    const currentDefaults = worldUnitDefaults(defaults, metadata?.worldUnitFields ?? []);
    // A replicated name that matches no field would silently sync nothing — the
    // drift class this metadata exists to kill, so it fails loud (same spirit as
    // EHT rejecting a malformed known annotation).
    for (const f of metadata?.replicatedFields ?? []) {
        if (!hasOwn(defaultsRec, f)) {
            throw new Error(`Component "${name}": replicatedFields names unknown field "${f}"`);
        }
    }
    // Same reason, and the same check EHT makes for a builtin: a renderableField
    // that names nothing would read as "draws nothing" and quietly stay visible.
    const renderableField = metadata?.renderableField;
    if (renderableField !== undefined && (!hasOwn(defaultsRec, renderableField) || typeof defaultsRec[renderableField] !== 'boolean')) {
        throw new Error(
            `Component "${name}": renderableField "${renderableField}" is not a boolean field of its defaults`,
        );
    }
    return {
        _id: componentId(name),
        _name: name,
        // In the project's units: what a default fills in follows its units per metre.
        get _default() { return currentDefaults(); },
        _builtin: false as const,
        assetFields: metadata?.assetFields ?? [],
        skeletalFields: metadata?.skeletalFields,
        entityFields: metadata?.entityFields ?? [],
        colorKeys: detectColorKeys(defaults),
        animatableFields: metadata?.animatableFields ?? numericAnimatableFields(defaults),
        replicatedFields: metadata?.replicatedFields ?? [],
        readonlyFields: metadata?.readonlyFields ?? [],
        fieldMeta: metadata?.fields ?? {},
        discoverAssets: metadata?.discoverAssets,
        transient: metadata?.transient ?? false,
        renderableField: renderableField ?? null,
        create(data?: Partial<T>): T {
            const now = currentDefaults();
            // Flat defaults have nothing to merge into, so they take the cheap path.
            if (keyInfo) return mergeIntoDefaults(now, data);
            return data ? { ...now, ...data } : { ...now };
        }
    };
}

// User components live in the per-app AppContext registry (reset-able). Builtins
// are global and live in `builtinRegistry` (declared further below). The public
// catalogue accessors merge the two — see getComponentRegistry().
function userComponents(): Map<string, AnyComponentDef> {
    return getDefaultContext().componentRegistry as Map<string, AnyComponentDef>;
}

/**
 * Declare a component type from its name and the defaults every instance starts
 * with. `name` is the identity a scene file stores, so it is what a saved entity
 * is rebound by; defining the same name twice returns the first definition
 * rather than replacing it, so a hot reload cannot orphan live entities.
 *
 * @throws if `name` is already taken by a built-in engine component.
 * @public
 */
export function defineComponent<T extends object>(
    name: string,
    defaults: T,
    metadata?: ComponentMetadata,
): ComponentDef<T> {
    const existing = userComponents().get(name);
    if (existing) {
        // Same fields is one declaration reached twice (two import paths, a hot
        // reload). DIFFERENT fields is two components claiming one name, and the
        // loser's fields are dropped from every scene that carries them.
        const had = Object.keys(existing._default as object).sort();
        const wants = Object.keys(defaults).sort();
        if (had.length !== wants.length || had.some((k, i) => k !== wants[i])) {
            throw new Error(
                `Component name collision: "${name}" is already defined with fields `
                + `[${had.join(', ')}], and this declaration has [${wants.join(', ')}]. `
                + 'One of them loses its fields wherever a scene carries them — rename one.',
            );
        }
        return existing as ComponentDef<T>;
    }

    if (builtinRegistry.has(name)) {
        throw new Error(
            `Component name collision: user component "${name}" conflicts with an existing builtin component of the same name`
        );
    }

    const def = createComponentDef(name, defaults, metadata);
    userComponents().set(name, def);
    componentRegistryVersion_++;
    registerToEditor(name, defaults as Record<string, unknown>, false);
    return def;
}

/**
 * Declare a component with no fields — a marker a query filters on. Returning
 * the existing definition for a name already declared is deliberate: a tag
 * carries no data, so re-declaring one cannot conflict with itself the way
 * {@link defineComponent} can.
 *
 * @public
 */
export function defineTag(name: string): ComponentDef<{}> {
    const existing = userComponents().get(name);
    if (existing) return existing as ComponentDef<{}>;

    if (builtinRegistry.has(name)) {
        throw new Error(
            `Component name collision: tag "${name}" conflicts with an existing builtin component of the same name`
        );
    }

    const def = createComponentDef(name, {});
    userComponents().set(name, def);
    componentRegistryVersion_++;
    registerToEditor(name, {}, true);
    return def;
}

export function getUserComponent(name: string): ComponentDef<any> | undefined {
    return userComponents().get(name) as ComponentDef<any> | undefined;
}

export function clearUserComponents(): void {
    userComponents().clear();
    componentRegistryVersion_++;
}

export function unregisterComponent(name: string): void {
    userComponents().delete(name);
    componentRegistryVersion_++;
}

// The engine's own `defineComponent`s (AI, animation, audio, physics joints, UI
// text, tilemap, timeline…) register at SDK module load into the per-app user
// registry. A hot reload only re-imports the PROJECT bundle — the cached `esengine`
// module does NOT re-run — so `clearUserComponents()` would drop these engine
// components with nothing to put them back. The SDK entry snapshots them once as a
// baseline; the hot-reload probe and app build re-seed it so engine components
// survive a reload (and the hot-swap fast path can match fingerprints).
let engineComponentBaseline_: Map<string, AnyComponentDef> | null = null;

/** Snapshot the currently-registered components as the engine baseline. Called
 *  once from the SDK entry after all engine `defineComponent`s have run and before
 *  any project bundle registers its own. */
export function markEngineComponentBaseline(): void {
    engineComponentBaseline_ = new Map(userComponents());
}

/**
 * Run @p declare, and count what it registers among the engine's own components. A part of the engine that lives in its own module (the Cocos
 * layer) registers components when it loads, after the entry took its baseline; without this a reload that clears the registry would drop them,
 * the module being cached and not loading again. Components the project declares are never added: they come from the project bundle, which a
 * reload does run again. No-op where no baseline was taken (a test that never loaded the SDK entry).
 */
export function declareAsEngineComponents(declare: () => void): void {
    const before = new Set(userComponents().keys());
    declare();
    if (!engineComponentBaseline_) return;
    for (const [name, def] of userComponents()) if (!before.has(name)) engineComponentBaseline_.set(name, def);
}

/** Re-add the engine baseline to a registry (only where missing), so a context
 *  that has never re-run the SDK's module-level registrations still has them.
 *  No-op until {@link markEngineComponentBaseline} has run (e.g. unit tests that
 *  never load the SDK entry). */
export function seedEngineComponents(registry: Map<string, AnyComponentDef> = userComponents()): void {
    if (!engineComponentBaseline_) return;
    for (const [name, def] of engineComponentBaseline_) if (!registry.has(name)) registry.set(name, def);
}

function registerToEditor(
    name: string,
    defaults: Record<string, unknown>,
    isTag: boolean
): void {
    getDefaultContext().editorBridge?.registerComponent(name, defaults, isTag);
}

// =============================================================================
// Builtin Component Definition (C++ backed)
// =============================================================================

/**
 * A component the engine ships, whose storage lives in C++. Carries the same
 * reflection a {@link ComponentDef} does, authored at the `ES_PROPERTY` site
 * instead of in a metadata argument, so tooling reads both the same way.
 *
 * @public
 */
export interface BuiltinComponentDef<T> {
    /** @internal */
    readonly _id: symbol;
    /** @internal */
    readonly _name: string;
    /** @internal */
    readonly _cppName: string;
    /** @internal */
    readonly _builtin: true;
    /** @internal */
    readonly _default: T;
    readonly assetFields: readonly AssetFieldMeta[];
    readonly skeletalFields?: SkeletalFieldMeta;
    readonly entityFields: readonly string[];
    readonly colorKeys: readonly string[];
    readonly animatableFields: readonly string[];
    /** Fields authored `replicated` at the C++ ES_PROPERTY site (via COMPONENT_META). */
    readonly replicatedFields: readonly string[];
    /** Fields authored `readonly` (engine-computed outputs); the editor never writes them back. */
    readonly readonlyFields: readonly string[];
    readonly fieldMeta: Readonly<Record<string, FieldMeta>>;
    readonly discoverAssets?: (data: Record<string, unknown>) => AssetRef[];
    /** Runtime-only: omitted from scene serialization. Authored `ES_COMPONENT(transient)`. */
    readonly transient: boolean;
    /** Bool field gating this component's visibility, or null if it draws nothing.
     *  Authored `ES_COMPONENT(renderable=<field>)`. */
    readonly renderableField: string | null;
}

// =============================================================================
// Component Type Union
// =============================================================================

/**
 * Either kind of component type: one a project declared, or one the engine
 * ships. Everything that takes "a component" takes this, so a query or a
 * command reads a built-in and a user component the same way.
 *
 * @public
 */
export type AnyComponentDef = ComponentDef<any> | BuiltinComponentDef<any>;

export function isBuiltinComponent(comp: AnyComponentDef): comp is BuiltinComponentDef<any> {
    return comp._builtin === true;
}

// Global builtin (C++-backed) component types — defined once at module load and
// shared across every context. User components are per-AppContext (see above).
const builtinRegistry = new Map<string, AnyComponentDef>();
let builtinRegistryVersion_ = 0;
let extraBuiltinCache_: { version: number; definitions: ReadonlyMap<string, AnyComponentDef> } | null = null;

export function registerComponent(name: string, def: AnyComponentDef): void {
    builtinRegistry.set(name, def);
    builtinRegistryVersion_++;
}

/** Complete catalogue: global builtins + the current context's user components. */
export function getComponentRegistry(): Map<string, AnyComponentDef> {
    const all = new Map<string, AnyComponentDef>(builtinRegistry);
    for (const [name, def] of userComponents()) all.set(name, def);
    return all;
}

/** @internal Shared builtin definitions, without constructing a merged catalogue. */
export function builtinComponentRegistry(): ReadonlyMap<string, AnyComponentDef> {
    return builtinRegistry;
}

/** @internal Definitions outside the generated core catalogue, refreshed on registration. */
export function extraBuiltinComponentRegistry(): ReadonlyMap<string, AnyComponentDef> {
    if (extraBuiltinCache_?.version === builtinRegistryVersion_) return extraBuiltinCache_.definitions;
    const definitions = new Map([...builtinRegistry].filter(([name]) => !hasOwn(COMPONENT_META, name)));
    extraBuiltinCache_ = { version: builtinRegistryVersion_, definitions };
    return definitions;
}

/** Just the current context's user/script components (excludes builtins). */
export function getUserComponents(): Map<string, AnyComponentDef> {
    return userComponents();
}

/**
 * A stable digest of the current context's user component schemas — each component's
 * name plus its default field shape (keys + value types, recursively). The hot-reload
 * fast path compares this across a project-bundle re-import: an unchanged digest means
 * only system logic changed (hot-swap, keep the live World); a changed digest means a
 * component's fields changed and the live data no longer matches the new schema, so the
 * realm must full-reload. Builtins are excluded (their C++-backed shape never changes).
 * Default *values* are intentionally not hashed — only the shape gates a rebuild.
 */
export function getUserComponentFingerprint(): string {
    const comps = userComponents();
    return [...comps.keys()].sort()
        .map((name) => `${name}:${fieldShape(comps.get(name)!._default)}`)
        .join('|');
}

function fieldShape(value: unknown): string {
    if (value === null || typeof value !== 'object') return typeof value;
    if (Array.isArray(value)) return `[${value.length ? fieldShape(value[0]) : ''}]`;
    const rec = value as Record<string, unknown>;
    return `{${Object.keys(rec).sort().map((k) => `${k}:${fieldShape(rec[k])}`).join(',')}}`;
}

export function getComponent(name: string): AnyComponentDef | undefined {
    return builtinRegistry.get(name) ?? userComponents().get(name);
}

/** A component's per-field editor presentation metadata (empty if none declared). */
export function getComponentFieldMeta(name: string): Readonly<Record<string, FieldMeta>> {
    return getComponent(name)?.fieldMeta ?? {};
}

/**
 * The fields the replication layer syncs for a component — builtin (C++
 * `replicated` annotation) and user (`replicatedFields` metadata) through one
 * accessor. Empty = the component never replicates.
 */
export function getReplicatedFields(name: string): readonly string[] {
    return getComponent(name)?.replicatedFields ?? [];
}

/** A component that gates its drawing on a bool field, so that field is known. */
export type RenderableComponentDef = AnyComponentDef & { readonly renderableField: string };

/** Bumped by every registry mutation in this module, so the derived views below
 *  can tell "same components as last time" from "looks the same". */
let componentRegistryVersion_ = 0;
let renderableCache_: {
    version: number;
    userMap: Map<string, AnyComponentDef>;
    userSize: number;
    builtinSize: number;
    list: readonly RenderableComponentDef[];
} | null = null;

/**
 * Every registered component taking part in an entity's visibility, with the field
 * that gates each. Derived per call — a project's own component registers long
 * after load. The memo key carries both registry sizes and the context's map
 * identity, so a mutation outside this module (reset, hot reload) still misses it.
 */
export function renderableComponents(): readonly RenderableComponentDef[] {
    const userMap = userComponents();
    const cached = renderableCache_;
    if (cached !== null
        && cached.version === componentRegistryVersion_
        && cached.userMap === userMap
        && cached.userSize === userMap.size
        && cached.builtinSize === builtinRegistry.size) {
        return cached.list;
    }
    const list: RenderableComponentDef[] = [];
    // Both halves directly rather than through getComponentRegistry(), whose
    // merged Map would be allocated and thrown away on every miss. A name cannot
    // be in both: defineComponent and defineBuiltin each refuse the collision.
    for (const def of builtinRegistry.values()) {
        if (def.renderableField !== null) list.push(def as RenderableComponentDef);
    }
    for (const def of userMap.values()) {
        if (def.renderableField !== null) list.push(def as RenderableComponentDef);
    }
    renderableCache_ = {
        version: componentRegistryVersion_,
        userMap,
        userSize: userMap.size,
        builtinSize: builtinRegistry.size,
        list,
    };
    return list;
}

/**
 * Per-field merge of two FieldMeta maps: `override` wins key-by-key *within* a field
 * (not whole-field replacement), so a builtin can author min/tooltip at the C++
 * ES_PROPERTY site (→ `base`) and still add a runtime-only `enum`/`flags` override in
 * TS without dropping the generated keys. See {@link defineBuiltin}.
 */
function mergeFieldMeta(
    base: Record<string, FieldMeta>,
    override: Record<string, FieldMeta>,
): Record<string, FieldMeta> {
    const out: Record<string, FieldMeta> = { ...base };
    for (const k of Object.keys(override)) {
        out[k] = { ...base[k], ...override[k] };
    }
    return out;
}

function detectColorKeys(defaults: unknown): readonly string[] {
    if (defaults === null || typeof defaults !== 'object') return [];
    const keys: string[] = [];
    for (const key of Object.keys(defaults as Record<string, unknown>)) {
        const val = (defaults as Record<string, unknown>)[key];
        if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
            const rec = val as Record<string, unknown>;
            if ('r' in rec && 'g' in rec && 'b' in rec && 'a' in rec) {
                keys.push(key);
            }
        }
    }
    return keys;
}

// Keyframeable fields for a user component (the Sequencer animates one number per
// track): top-level numbers plus one level of nested numbers (vec / color channels
// as dot-paths). So defineComponent('Patrol', { speed: 60 }) is animatable with no
// boilerplate; metadata.animatableFields overrides this.
function numericAnimatableFields(defaults: unknown): string[] {
    if (defaults === null || typeof defaults !== 'object') return [];
    const out: string[] = [];
    for (const [key, val] of Object.entries(defaults as Record<string, unknown>)) {
        if (typeof val === 'number') out.push(key);
        else if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
            for (const [sub, sval] of Object.entries(val as Record<string, unknown>)) {
                if (typeof sval === 'number') out.push(`${key}.${sub}`);
            }
        }
    }
    return out;
}

export function defineBuiltin<T>(name: string, defaults: T, metadata?: ComponentMetadata): BuiltinComponentDef<T> {
    const existing = builtinRegistry.get(name) ?? userComponents().get(name);
    if (existing) {
        if (existing._builtin) return existing as BuiltinComponentDef<T>;
        throw new Error(
            `Component name collision: builtin component "${name}" conflicts with an existing user component of the same name`
        );
    }

    const meta = COMPONENT_META[name];
    const currentDefaults = worldUnitDefaults(defaults, metadata?.worldUnitFields ?? BUILTIN_WORLD_UNIT_FIELDS[name] ?? []);
    const def: BuiltinComponentDef<T> = {
        _id: Symbol(`Builtin_${name}`),
        _name: name,
        _cppName: name,
        _builtin: true,
        // In the project's units: what a default fills in follows its units per metre.
        get _default() { return currentDefaults(); },
        assetFields: metadata?.assetFields ?? meta?.assetFields ?? [],
        skeletalFields: metadata?.skeletalFields ?? meta?.skeletal,
        entityFields: metadata?.entityFields ?? meta?.entityFields ?? [],
        colorKeys: meta?.colorFields ?? detectColorKeys(defaults),
        animatableFields: meta?.animatableFields ?? [],
        replicatedFields: meta?.replicatedFields ?? [],
        readonlyFields: meta?.readonlyFields ?? [],
        fieldMeta: mergeFieldMeta(meta?.fields ?? {}, metadata?.fields ?? {}),
        discoverAssets: metadata?.discoverAssets,
        transient: metadata?.transient ?? meta?.transient ?? false,
        renderableField: metadata?.renderableField ?? meta?.renderableField ?? null,
    };
    builtinRegistry.set(name, def);
    return def;
}

/**
 * Register every engine component in COMPONENT_META that doesn't already have a
 * typed builtin const below. COMPONENT_META is EHT-generated from the C++
 * `ES_COMPONENT` structs, so it is the single source of truth for *which*
 * components exist; this guarantees each one is registered — and therefore
 * loadable from a scene — even before someone hand-writes its typed
 * `export const`. Without this backstop a newly-added C++ component had metadata
 * + a binding but no registry entry, so `loadSceneData` silently dropped it.
 *
 * Idempotent (defineBuiltin no-ops on an already-registered builtin). The typed
 * consts below remain the ergonomic, type-checked overlay; this only fills gaps.
 * Called once from the package entry (index.ts / index.wechat.ts).
 */
export function ensureBuiltinComponentsRegistered(): void {
    for (const name of Object.keys(COMPONENT_META)) {
        if (!builtinRegistry.has(name)) {
            defineBuiltin(name, metaDefaults<Record<string, unknown>>(name));
        }
    }
}

// =============================================================================
// Camera / Canvas Enums
// =============================================================================

// Single-sourced from C++ ES_ENUMs (see import above). ProjectionType, ClearFlags,
// EmitterShape, SimulationSpace, LightType and ShapeType are re-exported from the
// generated module; their values and the editor dropdowns built from them now have
// one source.
export { ProjectionType, ClearFlags, EmitterShape, SimulationSpace, SubEmitterTrigger, ForceFieldType, ParticleColliderShape, LightType, ShapeType, SpriteMaskInteraction, SpriteDrawMode };

// Canonical values single-sourced from the C++ CanvasScaleMode enum (generated);
// ShowAll/NoBorder are Cocos-compat aliases with no C++ member.
export const ScaleMode = {
    FixedWidth: CanvasScaleMode.FixedWidth,
    FixedHeight: CanvasScaleMode.FixedHeight,
    Expand: CanvasScaleMode.Expand,
    Shrink: CanvasScaleMode.Shrink,
    Match: CanvasScaleMode.Match,
    ShowAll: CanvasScaleMode.Expand,
    NoBorder: CanvasScaleMode.Shrink,
} as const;

export type ScaleMode = (typeof ScaleMode)[keyof typeof ScaleMode];

// =============================================================================
// Builtin Component Types
// =============================================================================

// Data shapes whose fields are exactly the C++ struct — re-exported straight from
// the generated module (the single source). Adding/removing a C++ field flows here
// automatically; tsc then enforces every consumer matches.
export type {
    TransformData, SpriteData, ShapeRendererData, LightData, ShadowCaster2DData, DraggableData,
    SortingGroupData, GroupOpacityData, SpriteMaskData, LightProbeVolumeData, OccluderData,
    ReflectionProbeData, PlanarReflectionData,
    CanvasData, VelocityData, ParentData, ChildrenData, SpineAnimationData, DragonBonesAnimationData,
    TilemapLayerData, BitmapTextData, TrailRendererData, ParticleForceFieldData, ParticleColliderData, SpringBoneData, SpringBoneColliderData, BillboardData, ImpostorData,
};

export type LocalTransformData = TransformData;
export type WorldTransformData = TransformData;

// Camera = the generated C++ field shape + one editor-only field. `showFrustum`
// drives gizmo rendering and has no C++ Camera member, so it is added here rather
// than in the generated interface (the only hand-written Camera field).
/**
 * {@link Camera}'s fields, and one the editor adds.
 *
 * @beta
 */
export interface CameraData extends CameraDataCpp {
    showFrustum: boolean;
}

/**
 * {@link Name}'s single field. TS-only: the engine keeps names in its own index
 * rather than as a C++ component.
 *
 * @public
 */
export interface NameData {
    value: string;
}

export interface SceneOwnerData {
    scene: string;
    persistent: boolean;
}

// =============================================================================
// Builtin Component Instances
// =============================================================================

// Creation defaults = C++ ctor values ⊕ `editor_default=` annotation overrides
// (both EHT-generated) ⊕ TS-only-field overrides from the call site. This is the
// single place authoring defaults are assembled — a builtin's _default carries
// the merged result.
function metaDefaults<T>(name: string, overrides?: Partial<T>): T {
    const meta = COMPONENT_META[name];
    return {
        ...meta?.defaults,
        ...meta?.editorDefaults,
        ...overrides,
    } as T;
}

// Field presentation metadata (min/max/tooltip/category/…) is authored at the C++
// ES_PROPERTY site and flows in via COMPONENT_META.fields (RC9-1). Only metadata that
// can't be a static annotation — `enum`/`flags` built from a runtime TS constant, or a
// TS-only field with no C++ backing — stays here as a per-field override (deep-merged
// over the generated base by defineBuiltin).
/**
 * Where an entity is. `position`/`rotation`/`scale` are the authoring inputs,
 * relative to the parent; `worldPosition`/`worldRotation`/`worldScale` are what
 * the engine composed from them and must not be written back.
 *
 * @public
 */
export const Transform = defineBuiltin<TransformData>('Transform',
    metaDefaults<TransformData>('Transform')
);
/**
 * @deprecated A legacy spelling of {@link Transform} — the same component. Scene
 * loading normalises the name away, and both spellings will go at 1.0.
 */
export const LocalTransform = Transform;
/**
 * @deprecated A legacy spelling of {@link Transform} — the same component, whose
 * world fields it was once separate from. Read `Transform.worldPosition` instead.
 */
export const WorldTransform = Transform;

// size's authoring default (100×100 vs the {1,1} ctor value) is authored at the
// C++ ES_PROPERTY site (editor_default=) and merged in by metaDefaults.
/**
 * A textured quad. `size` is in world units and is the drawn extent — the texture
 * is stretched into it rather than deciding it — and `pivot` says where in that
 * rectangle the entity's position sits. `layer` is the painter order between
 * sprites; within a layer, storage order decides.
 *
 * @public
 */
export const Sprite = defineBuiltin<SpriteData>('Sprite',
    metaDefaults<SpriteData>('Sprite')
);

/**
 * Authored drag configuration, read by the drag system. Works on a UI node and
 * on a plain world-space sprite alike — the hit test answers for both.
 *
 * @experimental
 */
export const Draggable = defineBuiltin<DraggableData>('Draggable',
    metaDefaults<DraggableData>('Draggable')
);

// shapeType's dropdown is generated from the C++ ShapeType enum (ES_PROPERTY enum=).
export const ShapeRenderer = defineBuiltin<ShapeRendererData>('ShapeRenderer',
    metaDefaults<ShapeRendererData>('ShapeRenderer')
);

// type's dropdown is generated from the C++ LightType enum (ES_PROPERTY enum=).
export const Light = defineBuiltin<LightData>('Light',
    metaDefaults<LightData>('Light')
);

export const ShadowCaster2D = defineBuiltin<ShadowCaster2DData>('ShadowCaster2D',
    metaDefaults<ShadowCaster2DData>('ShadowCaster2D')
);

// A box of baked irradiance: what lights the things a lightmap cannot hold still.
// Typed because the viewport outlines it — a region of world nothing renders is a
// box a creator would otherwise place blind.
export const LightProbeVolume = defineBuiltin<LightProbeVolumeData>('LightProbeVolume',
    metaDefaults<LightProbeVolumeData>('LightProbeVolume')
);

/** A non-recursive planar capture, received by this entity's lit material. @experimental */
export const PlanarReflection = defineBuiltin<PlanarReflectionData>('PlanarReflection',
    metaDefaults<PlanarReflectionData>('PlanarReflection')
);

/**
 * A box inside which reflections come from a bake rather than from the sky: the
 * specular half of what LightProbeVolume answers. The atlas is the SCENE's and
 * `slot` says which column of it is here, so a room full of shiny things is still
 * one draw — a texture per probe would be a bind per draw.
 *
 * @experimental
 */
export const ReflectionProbe = defineBuiltin<ReflectionProbeData>('ReflectionProbe',
    metaDefaults<ReflectionProbeData>('ReflectionProbe')
);

/**
 * A box sight does not pass through: what stands behind it is not collected, and
 * the picture is unchanged. Authored, not taken from the geometry beside it — the
 * box has to lie INSIDE the wall, and bounds that contain a mesh claim the air at
 * its corners, where things would stop being drawn in front of the player.
 *
 * @experimental
 */
export const Occluder = defineBuiltin<OccluderData>('Occluder',
    metaDefaults<OccluderData>('Occluder')
);

/**
 * Turns this entity's `Sprite` into a stencil: the sprites drawn AFTER it that ask to be
 * masked (`Sprite.maskInteraction`) are cut by its shape. The mask's own sprite is not
 * drawn while it is masking — it is the cut, not a picture.
 */
export const SpriteMask = defineBuiltin<SpriteMaskData>('SpriteMask',
    metaDefaults<SpriteMaskData>('SpriteMask')
);

/**
 * Makes this entity and everything under it sort as ONE unit: the group states the
 * layer and order the whole subtree presents outward, and each member's own
 * `Sprite.order` becomes its place INSIDE the group. Nothing outside the group can
 * land between two of its members, which is what a per-sprite order cannot promise.
 */
export const SortingGroup = defineBuiltin<SortingGroupData>('SortingGroup',
    metaDefaults<SortingGroupData>('SortingGroup')
);

/**
 * Fades this entity and everything under it: the opacities multiply down the hierarchy into each descendant's own alpha,
 * the way `UINode.opacity` does for a UI subtree. It is not a composited layer — overlapping children show through one
 * another mid-fade.
 */
export const GroupOpacity = defineBuiltin<GroupOpacityData>('GroupOpacity',
    metaDefaults<GroupOpacityData>('GroupOpacity')
);

// The authoring defaults that differ from the C++ ctor (an active Orthographic
// at orthoSize 540 vs a Perspective/inactive runtime default) are authored at
// the C++ ES_PROPERTY sites (editor_default=) and merged in by metaDefaults.
// Only the TS-only field's default stays here.
/**
 * What a viewport draws and from where. One camera per render target;
 * `priority` breaks the tie and `isActive` takes one out.
 *
 * `@beta`: `clearFlags` is a bitmask whose C++ enum has no TypeScript spelling,
 * and `cullingMask` names layers no exported constant identifies — so two of
 * these fields are typed `number` for want of the vocabulary, not by design.
 *
 * @beta
 */
export const Camera = defineBuiltin<CameraData>('Camera',
    metaDefaults<CameraData>('Camera', {
        showFrustum: false,
    }),
    {
        fields: {
            // projectionType's dropdown is generated from the C++ ProjectionType enum.
            // clearFlags is a bitmask (ColorAndDepth = Color | Depth) — a curated bit
            // list (the C++ `flags` annotation suppresses the single-choice dropdown).
            clearFlags: { flags: [{ label: 'Color', value: 1 }, { label: 'Depth', value: 2 }] },
            // showFrustum is a TS-only editor field (no C++ Camera member), so its
            // metadata can't come from an annotation.
            showFrustum: {
                advanced: true,
                tooltip: 'Draw this camera\'s whole view volume in the editor, not just what it '
                    + 'frames on the content plane.',
            },
        },
    }
);

// All Canvas creation defaults (designResolution 1920×1080 / pixelsPerUnit 100 /
// scaleMode FixedHeight) match the C++ ctor, so they come straight from
// COMPONENT_META — no TS override to drift when C++ changes. scaleMode's dropdown
// is likewise generated from the C++ CanvasScaleMode enum.
export const Canvas = defineBuiltin<CanvasData>('Canvas',
    metaDefaults<CanvasData>('Canvas')
);

export const Velocity = defineBuiltin<VelocityData>('Velocity',
    metaDefaults<VelocityData>('Velocity')
);

/**
 * An entity's parent. The engine keeps this and {@link Children} in step, so
 * set the relationship through `world.setParent` rather than by writing either
 * side; a transform composes against whatever this names.
 *
 * @public
 */
export const Parent = defineBuiltin<ParentData>('Parent',
    metaDefaults<ParentData>('Parent')
);

/**
 * An entity's children, in order. The order is the draw order within a layer
 * for UI, and the engine maintains the list — {@link Parent} is the side to
 * write.
 *
 * @public
 */
export const Children = defineBuiltin<ChildrenData>('Children',
    metaDefaults<ChildrenData>('Children')
);

export const BitmapText = defineBuiltin<BitmapTextData>('BitmapText',
    metaDefaults<BitmapTextData>('BitmapText')
);

/**
 * A Spine skeleton on an entity — which skeleton and atlas, and what it is
 * playing. Driving it is {@link Spine}'s job; this is the data it drives.
 *
 * @beta
 */
export const SpineAnimation = defineBuiltin<SpineAnimationData>('SpineAnimation',
    metaDefaults<SpineAnimationData>('SpineAnimation')
);

export const DragonBonesAnimation = defineBuiltin<DragonBonesAnimationData>('DragonBonesAnimation',
    metaDefaults<DragonBonesAnimationData>('DragonBonesAnimation')
);

/**
 * Local-space geometry of a MeshRenderer renderable (triangle list, indexed).
 * `positions` is x,y pairs; `uvs` is u,v pairs (default 0,0); `colors` is r,g,b,a
 * floats (0-1) per vertex (default white). Uploaded via meshRenderer_setGeometry, which
 * validates indices engine-side.
 */
export interface MeshRendererGeometry {
    positions: number[];
    uvs?: number[];
    colors?: number[];
    indices: number[];
}

// MeshRenderer = the generated C++ field shape + one out-of-band TS-only field: the
// variable-size geometry payload has no fixed ABI offset, so it never crosses as a
// component field — it is uploaded through meshRenderer_setGeometry (see meshRendererPlugin's
// scene codec).
export interface MeshRendererData extends MeshRendererDataCpp {
    geometry: MeshRendererGeometry;
}

export const MeshRenderer = defineBuiltin<MeshRendererData>('MeshRenderer',
    metaDefaults<MeshRendererData>('MeshRenderer', { geometry: { positions: [], indices: [] } })
);

// Motion trail. Pure config — the point history is owned by the C++ TrailSystem and
// rendered as a ribbon by TrailPlugin; nothing crosses as a component field.
export const TrailRenderer = defineBuiltin<TrailRendererData>('TrailRenderer',
    metaDefaults<TrailRendererData>('TrailRenderer')
);

// Spring bones. Pure config: a chain's simulated state is owned by the C++ SpringBoneSystem, keyed by its root entity, and what it
// writes back is the local rotation of the bones under the root.
export const SpringBone = defineBuiltin<SpringBoneData>('SpringBone',
    metaDefaults<SpringBoneData>('SpringBone')
);
export const SpringBoneCollider = defineBuiltin<SpringBoneColliderData>('SpringBoneCollider',
    metaDefaults<SpringBoneColliderData>('SpringBoneCollider')
);

// A card that faces the camera. The renderer turns the MeshRenderer beside it to each view as the view collects it; the Transform is not written.
export const Billboard = defineBuiltin<BillboardData>('Billboard',
    metaDefaults<BillboardData>('Billboard')
);

// A picture of a mesh drawn in its place once it is small. The renderer draws the card; impostorPlugin takes the pictures.
export const Impostor = defineBuiltin<ImpostorData>('Impostor',
    metaDefaults<ImpostorData>('Impostor')
);

// Particle force field. A scene-placed zone (wind, attractor, vortex, drag) that the
// C++ ParticleSystem folds into every nearby world-space particle's integration.
export const ParticleForceField = defineBuiltin<ParticleForceFieldData>('ParticleForceField',
    metaDefaults<ParticleForceFieldData>('ParticleForceField')
);

// A shape particles bounce off with no physics: an emitter in `Sdf` collision mode, on the GPU or the CPU, asks its distance.
export const ParticleCollider = defineBuiltin<ParticleColliderData>('ParticleCollider',
    metaDefaults<ParticleColliderData>('ParticleCollider')
);

/**
 * One layer of a tile lattice: `cellSize` is its step in world units, and
 * `orientation` with the stagger fields cover isometric and hex, so it is not
 * only a square grid. The tiles are in a referenced `.estileset` rather than
 * here — render, collision and tile animation all derive from that.
 *
 * @beta
 */
export const TilemapLayer = defineBuiltin<TilemapLayerData>('TilemapLayer',
    metaDefaults<TilemapLayerData>('TilemapLayer'),
    {
        // A discoverAssets callback is the component's COMPLETE asset manifest
        // (assetFields are not walked for discovery when one is present), so it
        // must list both dependencies:
        // - `tileset`, the legacy copied atlas-texture ref (matches the generated
        //   assetField) — old scenes render from it directly;
        // - `tilesetAsset`, the out-of-band `.estileset` reference (see
        //   tilemapPlugin's scene codec). Preloading it up front lets the tilemap
        //   sync derive the render table, collision AND animation live from the
        //   tileset on the FIRST frame — no lazy-load gap, no baked
        //   `collidableTileIds` snapshot needed. This is the single-source model.
        discoverAssets: (data) => {
            const refs: AssetRef[] = [];
            const texture = data.tileset;
            if (typeof texture === 'string' && texture) refs.push({ type: 'texture', path: texture });
            // `tilesetAssets` (a list of `.estileset` refs) is the multi-tileset model;
            // fall back to the singular `tilesetAsset` for older single-tileset layers.
            const list = (data as { tilesetAssets?: unknown }).tilesetAssets;
            if (Array.isArray(list) && list.length > 0) {
                for (const r of list) if (typeof r === 'string' && r) refs.push({ type: 'tileset', path: r });
            } else {
                const ref = data.tilesetAsset;
                if (typeof ref === 'string' && ref) refs.push({ type: 'tileset', path: ref });
            }
            return refs;
        },
    },
);

// =============================================================================
// ParticleEmitter Enums
// =============================================================================

// EmitterShape, SimulationSpace and ParticleEasing are re-exported from the
// generated module (see the import at the top) — single-sourced from their C++
// ES_ENUMs beside the component fields that serialize them.
export { ParticleEasing, ParticleCollisionMode, ParticleCollisionFallback, ParticleRenderMode, ReflectionAxis, ReflectionQuality, ReflectionUpdate, BillboardMode };

// =============================================================================
// ParticleEmitter Component
// =============================================================================

/**
 * The generated C++ field shape plus two the simulation has no member for:
 * `colorGradient` and `sizeCurve` are authored in TypeScript and baked to a LUT
 * the sim reads (see particlePlugin's scene codec), which is why they live here
 * and not in the generated interface.
 *
 * @beta
 */
export interface ParticleEmitterData extends ParticleEmitterDataCpp {
    /**
     * Color-over-life gradient (authored stops). When it has stops it overrides
     * startColor/endColor + colorEasing. Empty ⇒ start/end fallback.
     */
    colorGradient: { stops: { t: number; color: Color }[] };
    /**
     * Size-over-life curve (a multiplier × start size, keys over [0,1]). When it
     * has keys it overrides startSize/endSize + sizeEasing. Empty ⇒ start/end fallback.
     */
    sizeCurve: { keys: { t: number; v: number }[] };
    /**
     * Bursts on a schedule: `count` particles once the emitter has been emitting for `time` seconds, repeated every
     * `duration` while it loops. Beside (not instead of) `burstCount`, which repeats one burst on an interval.
     */
    bursts: { time: number; count: number }[];
}

/**
 * A particle system on an entity. `colorGradient` and `sizeCurve` OVERRIDE the
 * start/end pairs when they carry stops or keys and fall back to them when
 * empty; `simulationSpace` decides whether particles follow the entity or are
 * left behind by it. Integration is C++, over the whole system at once.
 *
 * @beta
 */
export const ParticleEmitter = defineBuiltin<ParticleEmitterData>('ParticleEmitter',
    metaDefaults<ParticleEmitterData>('ParticleEmitter', { colorGradient: { stops: [] }, sizeCurve: { keys: [] }, bursts: [] }),
    {
        // Most field metadata is authored at the C++ ES_PROPERTY site (categories,
        // min/step, and the shape/simulationSpace/easing enum dropdowns via `enum=`).
        // Only what an annotation can't express stays here: the blendMode dropdown
        // (BlendMode is a renderer enum with no component ES_ENUM), and the two
        // TS-only editor fields (sizeCurve / colorGradient / bursts have no C++ member).
        fields: {
            blendMode: { enum: enumOptions(BlendMode) },
            sizeCurve: { curve: true, category: 'Size' },
            colorGradient: { gradient: true, category: 'Color' },
            bursts: { category: 'Emission' },
        },
    }
);

/**
 * Marks an entity inactive: it keeps its components and its place in the tree,
 * and every query skips it — which is how the systems skip it. A query that
 * NAMES this one sees them, since managing the switch means reaching what is
 * switched off; `setEntityActive` sets it, and takes the subtree with it.
 */
export const Disabled = defineTag('Disabled');

/**
 * Marks a world-only DERIVED entity — one a system (re)builds from source data
 * (the child layer entities a `Tilemap.source` projects, runtime tile
 * colliders, …). Scene serialization skips tagged entities entirely:
 * persisting one would duplicate it against the next derivation.
 *
 * @public
 */
export const RuntimeOnly = defineTag('RuntimeOnly');

/**
 * An entity's name — what the outliner shows and `findEntityByName` looks up.
 * Not an identity: nothing stops two entities sharing one.
 *
 * @public
 */
export const Name = defineComponent<NameData>('Name', { value: '' });

export const SceneOwner = defineComponent<SceneOwnerData>('SceneOwner', {
    scene: '',
    persistent: false,
});

export interface MarkerData {
    /** Gameplay identity — the game queries markers of a given kind (spawn point,
     *  waypoint, pickup, door, trigger …). Free-form: the game defines the vocabulary.
     *  `Query(Marker)` then filters by `type`. */
    type: string;
    /** Arbitrary per-marker gameplay data (team, targetScene, event, …), like Tiled's
     *  custom object properties. Imported `.tmj` object properties land here too. */
    properties: Record<string, string>;
}

/**
 * A named point/region of gameplay interest, placed in the editor as a real entity.
 * On its own (Transform + Marker) it's a spawn point / waypoint / location marker; add a
 * sensor collider (the Trigger Area preset) and it's a trigger zone. Pure ECS — no
 * parallel "object layer" structure — so it serializes, shows in the Inspector, and is
 * `Query`-able like any component. The converged target for imported `.tmj` object groups.
 */
export const Marker = defineComponent<MarkerData>('Marker', { type: '', properties: {} }, {
    // `properties` is an arbitrary string→string map — opt into the map editor (value-shape
    // inference would otherwise drop it as an unknown object).
    fields: { properties: { map: true } },
});

export interface PostProcessVolumeData {
    effects: {
        type: string;
        enabled: boolean;
        uniforms: Record<string, number>;
        /** Texture params (LUTs, masks): sampler uniform -> serialized texture ref. */
        textures?: Record<string, string>;
        /** Colour params (a fog colour): uniform -> RGBA. Blends like a float does,
         *  toward the effect's declared default at a volume's soft edge. */
        colors?: Record<string, { r: number; g: number; b: number; a: number }>;
    }[];
    isGlobal: boolean;
    shape: 'box' | 'sphere';
    /** Half-extents of the shape (a sphere uses `x` as its radius). `z` is the
     *  half-DEPTH of a box, where **0 means unbounded** — a flat scene's volume
     *  reaches through every depth, and a box of no thickness would contain
     *  nothing at all. */
    size: { x: number; y: number; z?: number };
    priority: number;
    weight: number;
    blendDistance: number;
}

export const PostProcessVolume = defineComponent<PostProcessVolumeData>('PostProcessVolume', {
    effects: [],
    isGlobal: true,
    shape: 'box',
    size: { x: 5, y: 5 },
    priority: 0,
    weight: 1,
    blendDistance: 0,
}, {
    // WHAT the volume applies. Every other field is about WHERE, and value-shape
    // inference drops a list of objects, so without this opt-in the whole effect
    // registry is a runtime the scene format carries and no panel can reach.
    fields: { effects: { effectStack: true } },
    // The COMPLETE asset manifest for discovery: effect texture params (LUTs,
    // masks) preload with the scene so the volume system's cache lookups hit.
    discoverAssets: (data) => {
        const refs: AssetRef[] = [];
        const effects = data.effects;
        if (Array.isArray(effects)) {
            for (const effect of effects) {
                const textures = (effect as { textures?: Record<string, unknown> }).textures;
                if (!textures) continue;
                for (const ref of Object.values(textures)) {
                    if (typeof ref === 'string' && ref) refs.push({ type: 'texture', path: ref });
                }
            }
        }
        return refs;
    },
});

export interface WeatherData {
    /** The weather the scene is in (the built-in presets: Clear, Mist, Overcast, Rain, Storm, Snow). */
    preset: number;
    /** The weather it is turning into; -1 for none. */
    target: number;
    /** How far along that turn it is, 0..1. The system advances it in play, and a value set here previews it in the editor. */
    progress: number;
    /** Seconds a turn takes. */
    duration: number;
    /** Presets to cycle through by themselves, by name or id, comma separated ("clear,mist,rain,clear"); empty = stay. */
    sequence: string;
    /** Seconds each weather of the sequence holds before the next turn begins. */
    hold: number;
    /** What the weather drives: lights, fog, rain, grade, exposure, reflections, sound, wind (plants and waves). */
    drive: number;
    /** An entity with a looping AudioSource — the sound of the rain. The weather sets its volume (the authored one times
     *  how hard it rains) and raises or lowers its `playing`. 0 = none. */
    soundSource: number;
}

const WEATHER_PRESET_OPTIONS = [
    { label: 'Clear', value: 0 }, { label: 'Mist', value: 1 }, { label: 'Overcast', value: 2 },
    { label: 'Rain', value: 3 }, { label: 'Storm', value: 4 }, { label: 'Snow', value: 5 },
];

/**
 * The weather of a scene: one of a few presets, a turn toward another, and an optional cycle between them.
 *
 * @details A preset is a handful of multipliers on what the scene already has — the sun at a fraction of its strength,
 *          the fog thicker, the picture a little greyer — and a few absolute levels (how hard it rains, how wet the ground
 *          is), so the same weather fits any project. The component drives the scene's lights (in play), the post-process
 *          effects its volumes resolve (rain, fog, grade, exposure, reflections) and the sound of the rain.
 */
export const Weather = defineComponent<WeatherData>('Weather', {
    preset: 0,
    target: -1,
    progress: 0,
    duration: 6,
    sequence: '',
    hold: 20,
    drive: 255,
    soundSource: 0,
}, {
    entityFields: ['soundSource'],
    fields: {
        preset: { enum: WEATHER_PRESET_OPTIONS },
        target: { enum: [{ label: 'None', value: -1 }, ...WEATHER_PRESET_OPTIONS] },
        progress: { min: 0, max: 1, step: 0.01 },
        duration: { min: 0.1, max: 600, step: 0.1, unit: 's' },
        hold: { min: 0, max: 3600, step: 1, unit: 's' },
        drive: { flags: [
            { label: 'Lights', value: 1 }, { label: 'Fog', value: 2 }, { label: 'Rain', value: 4 }, { label: 'Grade', value: 8 },
            { label: 'Exposure', value: 16 }, { label: 'Reflections', value: 32 }, { label: 'Sound', value: 64 },
            { label: 'Wind', value: 128 },
        ] },
    },
});

export interface TimeOfDayData {
    /** The hour of the day, 0..24 (12 is noon). The system advances it in play, and a value set here previews it in the editor. */
    hour: number;
    /** Seconds a whole day takes while the game runs; 0 holds the hour where it is. */
    daySeconds: number;
    /** Where on the planet, in degrees (positive north): how high the noon sun climbs and how long a day is. */
    latitude: number;
    /** The season, in degrees, -23.5 (winter) .. 23.5 (summer) in the north. */
    declination: number;
    /** How far the world is turned from compass north (+Z) toward +X, in degrees: which way the sun rises. */
    north: number;
    /** What the time drives: the lights, the sky, the fog, the exposure, the reflections. */
    drive: number;
}

/**
 * The time of day of a scene: where the sun and the moon are, and what the light, the sky and the fog are because of it.
 *
 * @details The sun crosses the sky along the path its latitude and the season give it; the scene's directional light is aimed
 *          at it (at the moon by night) and scaled by a day's curve — warm and weak near the horizon, gone once it is down — and
 *          the ambient light follows. A Sky Atmosphere effect draws the sun, a dusk glow, a moon and stars where it stands,
 *          and the fog is lit as the day is. It composes with Weather: both scale the same lights from what the author set.
 */
export const TimeOfDay = defineComponent<TimeOfDayData>('TimeOfDay', {
    hour: 12,
    daySeconds: 0,
    latitude: 40,
    declination: 15,
    north: 0,
    drive: 31,
}, {
    fields: {
        hour: { min: 0, max: 24, step: 0.05, unit: 'h' },
        daySeconds: { min: 0, max: 86400, step: 1, unit: 's' },
        latitude: { min: -90, max: 90, step: 1, unit: 'deg' },
        declination: { min: -23.5, max: 23.5, step: 0.5, unit: 'deg' },
        north: { min: -180, max: 180, step: 1, unit: 'deg' },
        drive: { flags: [
            { label: 'Lights', value: 1 }, { label: 'Sky', value: 2 }, { label: 'Fog', value: 4 },
            { label: 'Exposure', value: 8 }, { label: 'Reflections', value: 16 },
        ] },
    },
});

export type {
    RigidBody2DData, BoxCollider2DData, CircleCollider2DData, CapsuleCollider2DData,
};

// =============================================================================
// Type Helpers
// =============================================================================

/**
 * The value shape a component definition holds — `ComponentData<typeof Transform>`
 * is `TransformData`. This is what `world.get` answers and `world.set` takes, so a
 * helper generic over a component writes its own signature with it.
 *
 * @public
 */
export type ComponentData<C> =
    C extends BuiltinComponentDef<infer T> ? T :
    C extends ComponentDef<infer T> ? T :
    never;

// =============================================================================
// Component Defaults Registry
// =============================================================================

export function getComponentDefaults(typeName: string): Record<string, unknown> | null {
    const comp = getComponent(typeName);
    if (comp) return deepClone(comp._default);
    return null;
}