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.

22.8 KB
Raw Blame
"""Emscripten embind C++ bindings generator."""

from typing import List, Set
from ..registry_ops import REGISTRY_OPS
from ..data import Component, Enum, HIERARCHY_COMPONENTS, READ_HOOKS
from ..type_system import TypeSystem


class EmbindGenerator:
    def __init__(self, components: List[Component], enums: List[Enum],
                 layout_asserts: str = '', abi_hash: str = ''):
        self.components = components
        self.enums = enums
        self.types = TypeSystem(enums)
        # C++ static_assert(offsetof) block from PtrLayoutGenerator, and the
        # single-source-of-truth ABI hash. Both injected so the boundary
        # contract lives in one generated TU. See tools/eht/abi.py.
        self.layout_asserts = layout_asserts
        self.abi_hash = abi_hash

    def generate(self) -> str:
        lines = self._gen_header()
        lines.extend(self._gen_includes())
        lines.extend(self._gen_math_types())
        lines.extend(self._gen_enums())
        lines.extend(self._gen_components())
        lines.extend(self._gen_registry())
        lines.extend(self._gen_reflection())
        lines.extend(self._gen_layout_asserts())
        lines.extend(self._gen_abi_hash())
        lines.append('')
        return '\n'.join(lines)

    def _gen_layout_asserts(self) -> List[str]:
        if not self.layout_asserts:
            return []
        return ['', self.layout_asserts]

    def _gen_abi_hash(self) -> List[str]:
        """Emit getAbiLayoutHash() — the runtime half of the boundary contract.

        Returns the same digest EHT baked into the TS bundle as ABI_LAYOUT_HASH.
        The SDK compares them at connect() and refuses to run on mismatch."""
        return [
            '',
            '// =============================================================================',
            '// ABI Hash -- runtime handshake against the SDK bundle',
            '// =============================================================================',
            '',
            f'static const char* kEsAbiLayoutHash = "{self.abi_hash}";',
            '',
            'std::string esengineGetAbiLayoutHash() {',
            '    return std::string(kEsAbiLayoutHash);',
            '}',
            '',
            'EMSCRIPTEN_BINDINGS(esengine_abi) {',
            '    emscripten::function("getAbiLayoutHash", &esengineGetAbiLayoutHash);',
            '}',
        ]

    def _gen_header(self) -> List[str]:
        return [
            '/**',
            ' * @file    WebBindings.generated.cpp',
            ' * @brief   Auto-generated Emscripten embind bindings',
            ' * @details Generated by EHT - DO NOT EDIT',
            ' */',
            '',
            '#include <emscripten/bind.h>',
            '#include <cstddef>',
            '#include <string>',
            '#include "../ecs/Registry.hpp"',
            '#include "../math/Math.hpp"',
            '#include "../ui/UITypes.hpp"',
        ]

    def _gen_includes(self) -> List[str]:
        headers: Set[str] = set()
        for comp in self.components:
            if comp.header_path and 'src/esengine/' in comp.header_path:
                rel = '../' + comp.header_path.replace('\\', '/').split('src/esengine/')[-1]
                headers.add(f'#include "{rel}"')
        # Enums too: one declared away from any component is registered by
        # its C++ type all the same, and without this the TU cannot name it.
        for enum in self.enums:
            if enum.header_path and 'src/esengine/' in enum.header_path:
                rel = '../' + enum.header_path.replace('\\', '/').split('src/esengine/')[-1]
                headers.add(f'#include "{rel}"')
        headers.add('#include "../ecs/TransformSystem.hpp"')
        lines = sorted(headers)
        lines.extend([
            '',
            'using namespace emscripten;',
            'using namespace esengine;',
            'using namespace esengine::ecs;',
            '',
        ])
        return lines

    def _gen_math_types(self) -> List[str]:
        lines = [
            '// =============================================================================',
            '// Math Types',
            '// =============================================================================',
            '',
            'EMSCRIPTEN_BINDINGS(esengine_math) {',
            '    value_object<glm::vec2>("Vec2")',
            '        .field("x", &glm::vec2::x)',
            '        .field("y", &glm::vec2::y);',
            '',
            '    value_object<glm::vec3>("Vec3")',
            '        .field("x", &glm::vec3::x)',
            '        .field("y", &glm::vec3::y)',
            '        .field("z", &glm::vec3::z);',
            '',
            '    value_object<glm::vec4>("Vec4")',
            '        .field("x", &glm::vec4::x)',
            '        .field("y", &glm::vec4::y)',
            '        .field("z", &glm::vec4::z)',
            '        .field("w", &glm::vec4::w);',
            '',
            '    value_object<glm::uvec2>("UVec2")',
            '        .field("x", &glm::uvec2::x)',
            '        .field("y", &glm::uvec2::y);',
            '',
            '    value_object<glm::quat>("Quat")',
            '        .field("w", &glm::quat::w)',
            '        .field("x", &glm::quat::x)',
            '        .field("y", &glm::quat::y)',
            '        .field("z", &glm::quat::z);',
        ]
        # Registered POD structs (Padding, Dimension, ...) — one value_object each,
        # driven by the type-system registry so a new struct needs no codegen edit.
        for name, members in self.types.CUSTOM_STRUCTS.items():
            lines.append('')
            lines.append(f'    value_object<esengine::{name}>("{name}")')
            for i, (member, _) in enumerate(members):
                term = ';' if i == len(members) - 1 else ''
                lines.append(f'        .field("{member}", &esengine::{name}::{member}){term}')
        lines.extend([
            '}',
            '',
        ])
        return lines

    def _gen_enums(self) -> List[str]:
        if not self.enums:
            return []
        lines = [
            '// =============================================================================',
            '// Enums',
            '// =============================================================================',
            '',
            'EMSCRIPTEN_BINDINGS(esengine_enums) {',
        ]
        for enum in self.enums:
            full = f'{enum.namespace}::{enum.name}' if enum.namespace else enum.name
            lines.append(f'    enum_<{full}>("{enum.name}")')
            for val in enum.values:
                lines.append(f'        .value("{val}", {full}::{val})')
            lines[-1] += ';'
            lines.append('')
        lines.append('}')
        lines.append('')
        return lines

    def _gen_components(self) -> List[str]:
        lines = [
            '// =============================================================================',
            '// Components',
            '// =============================================================================',
            '',
        ]

        for comp in self.components:
            if not self.types.needs_wrapper(comp):
                continue

            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            js = f'{comp.name}JS'

            lines.append(f'struct {js} {{')
            for prop in comp.properties:
                if self.types.is_skip(prop.cpp_type):
                    continue
                js_type = self.types.get_js_type(prop.cpp_type)
                if self.types.is_struct_vector(prop.cpp_type):
                    # val has no default ctor usable for `{}` aggregate init.
                    lines.append(f'    {js_type} {prop.name} = emscripten::val::array();')
                else:
                    lines.append(f'    {js_type} {prop.name};')
            lines.append('};')
            lines.append('')

            # A hierarchy component is never written field-wise — setParent owns
            # both halves — so only the read direction is generated for it.
            if comp.name in HIERARCHY_COMPONENTS:
                lines.extend(self._gen_to_js(comp, full, js))
                continue

            # Assign onto an existing component rather than build a new one: a
            # component may carry engine-computed state that no ES_PROPERTY
            # declares (UIVisual.uiOrder, UINode.computed_size_), and replacing
            # the whole struct resets it.
            lines.append(f'void {comp.name.lower()}ApplyJS({full}& c, const {js}& js) {{')
            for prop in comp.properties:
                if self.types.is_skip(prop.cpp_type):
                    continue
                t = self.types.clean_type(prop.cpp_type)
                if self.types.is_handle(t):
                    lines.append(f'    c.{prop.name} = {t}(js.{prop.name});')
                elif self.types.is_entity(t):
                    lines.append(f'    c.{prop.name} = Entity(js.{prop.name});')
                elif self.types.is_enum(t):
                    lines.append(f'    c.{prop.name} = static_cast<{t}>(js.{prop.name});')
                elif t in self.types.VECTOR_TYPES and self.types.VECTOR_TYPES[t][0] == 'u32' and 'Entity' in t:
                    # Cleared: this writes into a component that already exists on every write after the first.
                    lines.append(f'    c.{prop.name}.clear();')
                    lines.append(f'    c.{prop.name}.reserve(js.{prop.name}.size());')
                    lines.append(f'    for (auto v : js.{prop.name}) c.{prop.name}.push_back(Entity(v));')
                elif self.types.is_struct_vector(t):
                    elem = self.types.vector_elem_cpp(t)
                    lines.append(f'    {{ const size_t n = js.{prop.name}["length"].as<size_t>();')
                    lines.append(f'      c.{prop.name}.clear(); c.{prop.name}.reserve(n);')
                    lines.append(f'      for (size_t i = 0; i < n; ++i) c.{prop.name}.push_back(js.{prop.name}[i].as<{elem}>()); }}')
                else:
                    lines.append(f'    c.{prop.name} = js.{prop.name};')
            lines.append('}')
            lines.append('')

            lines.append(f'{full} {comp.name.lower()}FromJS(const {js}& js) {{')
            lines.append(f'    {full} c;')
            lines.append(f'    {comp.name.lower()}ApplyJS(c, js);')
            lines.append('    return c;')
            lines.append('}')
            lines.append('')

            lines.extend(self._gen_to_js(comp, full, js))

        lines.append('EMSCRIPTEN_BINDINGS(esengine_components) {')

        registered_vectors: Set[str] = set()
        for comp in self.components:
            for prop in comp.properties:
                t = self.types.clean_type(prop.cpp_type)
                if t in self.types.VECTOR_TYPES:
                    elem_type, js_name, _ = self.types.VECTOR_TYPES[t]
                    if js_name not in registered_vectors:
                        lines.append(f'    register_vector<{elem_type}>("{js_name}");')
                        lines.append('')
                        registered_vectors.add(js_name)
                # Struct-vectors (std::vector<VisualState>) marshal as a JS array via
                # emscripten::val in the wrapper from/toJS — no register_vector needed.

        for comp in self.components:
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            needs_wrap = self.types.needs_wrapper(comp)
            bind = f'{comp.name}JS' if needs_wrap else full

            lines.append(f'    value_object<{bind}>("{comp.name}")')
            for prop in comp.properties:
                if self.types.is_skip(prop.cpp_type):
                    continue
                lines.append(f'        .field("{prop.name}", &{bind}::{prop.name})')
            lines[-1] += ';'
            lines.append('')
        lines.append('}')
        lines.append('')
        return lines

    def _gen_reflection(self) -> List[str]:
        """Emit a module-level function returning the authoritative list of
        component names bound in this WASM build. JS uses this to detect drift
        between the shipped SDK's COMPONENT_META and the actual WASM module."""
        lines = [
            '',
            '// =============================================================================',
            '// Reflection — authoritative binding manifest for JS',
            '// =============================================================================',
            '',
            'emscripten::val esengineGetBuiltinComponentNames() {',
            '    using namespace emscripten;',
            '    auto arr = val::array();',
            '    size_t i = 0;',
        ]
        for comp in self.components:
            lines.append(f'    arr.set(i++, val(std::string("{comp.name}")));')
        lines.extend([
            '    return arr;',
            '}',
            '',
            'EMSCRIPTEN_BINDINGS(esengine_reflection) {',
            '    emscripten::function("getBuiltinComponentNames", &esengineGetBuiltinComponentNames);',
            '}',
        ])
        return lines

    def _gen_to_js(self, comp: Component, full: str, js: str) -> List[str]:
        lines = [
            f'{js} {comp.name.lower()}ToJS(const {full}& c) {{',
            f'    {js} js;',
        ]
        for prop in comp.properties:
            if self.types.is_skip(prop.cpp_type):
                continue
            t = self.types.clean_type(prop.cpp_type)
            if self.types.is_handle(prop.cpp_type):
                lines.append(f'    js.{prop.name} = c.{prop.name}.id();')
            elif self.types.is_entity(prop.cpp_type):
                lines.append(f'    js.{prop.name} = static_cast<u32>(c.{prop.name});')
            elif self.types.is_enum(prop.cpp_type):
                lines.append(f'    js.{prop.name} = static_cast<i32>(c.{prop.name});')
            elif t in self.types.VECTOR_TYPES and self.types.VECTOR_TYPES[t][0] == 'u32' and 'Entity' in t:
                lines.append(f'    js.{prop.name}.reserve(c.{prop.name}.size());')
                lines.append(f'    for (auto e : c.{prop.name}) js.{prop.name}.push_back(static_cast<u32>(e));')
            elif self.types.is_struct_vector(t):
                lines.append(f'    js.{prop.name} = emscripten::val::array();')
                lines.append(f'    for (size_t i = 0; i < c.{prop.name}.size(); ++i) js.{prop.name}.set(i, emscripten::val(c.{prop.name}[i]));')
            else:
                lines.append(f'    js.{prop.name} = c.{prop.name};')
        lines.extend(['    return js;', '}', ''])
        return lines

    def _gen_hierarchy_writers(self, name: str, full: str, js: str) -> List[str]:
        if name == 'Parent':
            return [
                f'        .function("add{name}", optional_override([](Registry& r, u32 e, const {js}& js) {{',
                '            auto entity = static_cast<Entity>(e);',
                '            if (!r.valid(entity)) return;',
                '            esengine::ecs::setParent(r, entity, static_cast<Entity>(js.entity));',
                '        }))',
                f'        .function("remove{name}", optional_override([](Registry& r, u32 e) {{',
                '            auto entity = static_cast<Entity>(e);',
                f'            if (!r.valid(entity) || !r.has<{full}>(entity)) return;',
                '            esengine::ecs::setParent(r, entity, INVALID_ENTITY);',
                '        }))',
            ]
        return [
            f'        .function("add{name}", optional_override([](Registry& r, u32 e, const {js}& js) {{',
            '            auto entity = static_cast<Entity>(e);',
            '            if (!r.valid(entity)) return;',
            '            for (auto v : js.entities) {',
            '                esengine::ecs::setParent(r, static_cast<Entity>(v), entity);',
            '            }',
            '        }))',
            f'        .function("remove{name}", optional_override([](Registry& r, u32 e) {{',
            '            auto entity = static_cast<Entity>(e);',
            f'            if (!r.valid(entity) || !r.has<{full}>(entity)) return;',
            f'            const auto kids = r.get<{full}>(entity).entities;',
            '            for (auto child : kids) {',
            '                esengine::ecs::setParent(r, child, INVALID_ENTITY);',
            '            }',
            '        }))',
        ]

    def _gen_registry_ops(self) -> List[str]:
        """The entity ops, from the one table every backend reads (registry_ops)."""
        lines = []
        for op in REGISTRY_OPS:
            params = ''.join(f', {"bool" if k == "bool" else "u32"} {n}' for n, k in op.params)
            args = [f'static_cast<Entity>({n})' if k == 'entity' else n for n, k in op.params]
            call = op.call.format(*args)
            body = (f'{call};' if op.returns == 'void'
                    else f'return static_cast<u32>({call});' if op.returns == 'entity'
                    else f'return {call};')
            lines.append(f'        .function("{op.name}", optional_override([](Registry& r{params}) {{ {body} }}))')
        return lines

    def _gen_registry(self) -> List[str]:
        lines = [
            '// =============================================================================',
            '// Registry',
            '// =============================================================================',
            '',
            'EMSCRIPTEN_BINDINGS(esengine_registry) {',
            '    class_<Registry>("Registry")',
            '        .constructor<>()',
        ]
        lines.extend(self._gen_registry_ops())
        lines.append('')

        lines.extend([
            '        .function("getBuiltinComponentNames", optional_override([](Registry& r, u32 e) {',
            '            const auto entity = static_cast<Entity>(e);',
            '            std::string names;',
        ])
        for comp in self.components:
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            lines.append(f'            if (r.has<{full}>(entity)) {{ if (!names.empty()) names += "|"; names += "{comp.name}"; }}')
        lines.extend(['            return names;', '        }))', ''])
        lines.append('        .function("componentTypeId", optional_override([](Registry&, const std::string& name) {')
        for comp in self.components:
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            lines.append(f'            if (name == "{comp.name}") return static_cast<int>(componentTypeId<{full}>());')
        lines.extend(['            return -1;', '        }))', ''])

        for comp in self.components:
            full = f'{comp.namespace}::{comp.name}' if comp.namespace else comp.name
            name = comp.name
            needs_wrap = self.types.needs_wrapper(comp)
            js = f'{name}JS'
            from_js = f'{name.lower()}FromJS'
            to_js = f'{name.lower()}ToJS'

            lines.append(f'        // {name}')
            lines.append(f'        .function("has{name}", optional_override([](Registry& r, u32 e) {{')
            lines.append(f'            return r.has<{full}>(static_cast<Entity>(e));')
            lines.append('        }))')

            read_hook = READ_HOOKS.get(name)

            if name in HIERARCHY_COMPONENTS:
                lines.append(f'        .function("get{name}", optional_override([](Registry& r, u32 e) {{')
                lines.append(f'            auto entity = static_cast<Entity>(e);')
                lines.append(f'            if (!r.valid(entity) || !r.has<{full}>(entity)) return {js}{{}};')
                lines.append(f'            return {to_js}(r.get<{full}>(entity));')
                lines.append('        }))')
                lines.extend(self._gen_hierarchy_writers(name, full, js))
                lines.append('')
                continue

            if needs_wrap:
                lines.append(f'        .function("get{name}", optional_override([](Registry& r, u32 e) {{')
                lines.append(f'            auto entity = static_cast<Entity>(e);')
                lines.append(f'            if (!r.valid(entity) || !r.has<{full}>(entity)) return {js}{{}};')
                if read_hook:
                    lines.append(f'            auto& c = r.get<{full}>(entity);')
                    lines.append(f'            c.{read_hook}();')
                    lines.append(f'            return {to_js}(c);')
                else:
                    lines.append(f'            return {to_js}(r.get<{full}>(entity));')
                lines.append('        }))')
                lines.append(f'        .function("add{name}", optional_override([](Registry& r, u32 e, const {js}& js) {{')
                lines.append(f'            auto entity = static_cast<Entity>(e);')
                lines.append(f'            if (!r.valid(entity)) return;')
                lines.append(f'            if (auto* existing = r.tryGet<{full}>(entity)) {{')
                lines.append(f'                {name.lower()}ApplyJS(*existing, js);')
                lines.append(f'                return;')
                lines.append('            }')
                lines.append(f'            r.emplaceOrReplace<{full}>(entity, {from_js}(js));')
                lines.append('        }))')
            else:
                lines.append(f'        .function("get{name}", optional_override([](Registry& r, u32 e) -> {full}& {{')
                lines.append(f'            auto entity = static_cast<Entity>(e);')
                lines.append(f'            static {full} s_dummy{{}};')
                lines.append(f'            if (!r.valid(entity) || !r.has<{full}>(entity)) return s_dummy;')
                if read_hook:
                    lines.append(f'            auto& c = r.get<{full}>(entity);')
                    lines.append(f'            c.{read_hook}();')
                    lines.append(f'            return c;')
                else:
                    lines.append(f'            return r.get<{full}>(entity);')
                lines.append('        }), allow_raw_pointers())')
                lines.append(f'        .function("add{name}", optional_override([](Registry& r, u32 e, const {full}& c) {{')
                lines.append(f'            auto entity = static_cast<Entity>(e);')
                lines.append(f'            if (!r.valid(entity)) return;')
                lines.append(f'            r.emplaceOrReplace<{full}>(entity, c);')
                lines.append('        }))')

            lines.append(f'        .function("remove{name}", optional_override([](Registry& r, u32 e) {{')
            lines.append(f'            auto entity = static_cast<Entity>(e);')
            lines.append(f'            if (!r.valid(entity) || !r.has<{full}>(entity)) return;')
            lines.append(f'            r.remove<{full}>(entity);')
            lines.append('        }))')
            lines.append('')

        lines.append('        ;')
        lines.append('}')
        return lines