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.0 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    Physics.ts
 * @brief   User-facing physics API + Physics resource
 *
 * `Physics2DAPI` is the ergonomic wrapper game code uses to drive bodies
 * (forces, impulses, joints, raycasts). It is published as the
 * `Physics` resource once `Physics2DPlugin` finishes loading the
 * wasm module; instantiation before that throws.
 */

import type { App } from '../app/app';
import type { Entity, Vec2 } from '../types';
import { defineResource } from '../ecs/resource';
import type { PhysicsWasmModule } from './PhysicsModuleLoader';
import { Physics2DRuntime } from './Physics2DRuntime';
import { Physics2DDebugDraw, type Physics2DDebugDrawConfig } from './Physics2DDebugDraw';
import {
    CAST_HIT_STRIDE,
    type RaycastHit,
    type ShapeCastHit,
    type MassData,
    type MoverResult,
    type MoverOptions,
} from './PhysicsTypes';

// =============================================================================
// Physics API Helper
// =============================================================================

/** World pixels per Box2D meter, until a Canvas says otherwise. */
const DEFAULT_PIXELS_PER_UNIT = 100;

/**
 * Unit contract: Box2D simulates in meters; the engine converts at the
 * pixels-per-unit (PPU) boundary. Spatial *queries* (`raycast` / `shapeCast` /
 * `overlapCircle` / `moveCharacter`) take and return **world pixels**, scaled by
 * the live PPU. Everything that talks to the solver directly — forces, impulses,
 * velocities, `setGravity` — is in **meters** (m/s, m/s²), matching the collider
 * component dimensions. Convert with {@link getPixelsPerUnit} when mixing the two.
 */
export class Physics2DAPI {
    private module_!: PhysicsWasmModule;
    // Live pixels-per-unit, pushed each frame by PhysicsSystem from the Canvas, so
    // a query that omits `ppu` is scaled correctly instead of silently assuming 100.
    private ppu_!: number;

    /**
     * Starting state for both construction paths. `_fromModule` uses `Object.create`,
     * which runs no field initializer — a default declared as `ppu_ = 100` would be
     * `undefined` there.
     */
    private init_(module: PhysicsWasmModule): void {
        this.module_ = module;
        this.ppu_ = DEFAULT_PIXELS_PER_UNIT;
    }

    /** @internal Update the pixels-per-unit used to scale queries by default. */
    setPixelsPerUnit(ppu: number): void {
        if (Number.isFinite(ppu) && ppu > 0) this.ppu_ = ppu;
    }

    /**
     * Live pixels-per-unit (world pixels per Box2D meter). Collider dimensions are
     * stored in meters, so consumers that cast a collider's shape through the
     * pixel-space query API (raycast/shapeCast) must scale by this.
     */
    getPixelsPerUnit(): number {
        return this.ppu_;
    }

    constructor(app: App) {
        const module = app.hasResource(Physics2DRuntime)
            ? app.getResource(Physics2DRuntime).module
            : null;
        if (!module) {
            throw new Error('Physics module not loaded. Ensure Physics2DPlugin init is complete.');
        }
        this.init_(module);
    }

    /** @internal */
    static _fromModule(module: PhysicsWasmModule): Physics2DAPI {
        const instance = Object.create(Physics2DAPI.prototype) as Physics2DAPI;
        instance.init_(module);
        return instance;
    }

    applyForce(entity: Entity, force: Vec2): void {
        this.module_._physics_applyForce(entity, force.x, force.y);
    }

    applyImpulse(entity: Entity, impulse: Vec2): void {
        this.module_._physics_applyImpulse(entity, impulse.x, impulse.y);
    }

    setLinearVelocity(entity: Entity, velocity: Vec2): void {
        this.module_._physics_setLinearVelocity(entity, velocity.x, velocity.y);
    }

    getLinearVelocity(entity: Entity): Vec2 {
        const ptr = this.module_._physics_getLinearVelocity(entity);
        const base = ptr >> 2;
        return { x: this.module_.HEAPF32[base], y: this.module_.HEAPF32[base + 1] };
    }

    /** World gravity in **meters/s²** (Box2D space), e.g. `{ x: 0, y: -9.81 }`. */
    setGravity(gravity: Vec2): void {
        this.module_._physics_setGravity(gravity.x, gravity.y);
    }

    getGravity(): Vec2 {
        const ptr = this.module_._physics_getGravity();
        const base = ptr >> 2;
        return { x: this.module_.HEAPF32[base], y: this.module_.HEAPF32[base + 1] };
    }

    setAngularVelocity(entity: Entity, omega: number): void {
        this.module_._physics_setAngularVelocity(entity, omega);
    }

    getAngularVelocity(entity: Entity): number {
        return this.module_._physics_getAngularVelocity(entity);
    }

    applyTorque(entity: Entity, torque: number): void {
        this.module_._physics_applyTorque(entity, torque);
    }

    applyAngularImpulse(entity: Entity, impulse: number): void {
        this.module_._physics_applyAngularImpulse(entity, impulse);
    }

    createRevoluteJoint(
        entityA: Entity, entityB: Entity,
        anchorA: Vec2, anchorB: Vec2,
        options?: {
            enableMotor?: boolean; motorSpeed?: number; maxMotorTorque?: number;
            enableLimit?: boolean; lowerAngle?: number; upperAngle?: number;
            collideConnected?: boolean;
        }
    ): boolean {
        const o = options ?? {};
        return this.module_._physics_createRevoluteJoint(
            entityA, entityB,
            anchorA.x, anchorA.y, anchorB.x, anchorB.y,
            o.enableMotor ? 1 : 0, o.motorSpeed ?? 0, o.maxMotorTorque ?? 0,
            o.enableLimit ? 1 : 0, o.lowerAngle ?? 0, o.upperAngle ?? 0,
            o.collideConnected ? 1 : 0,
        ) !== 0;
    }

    destroyJoint(entity: Entity): void {
        this.module_._physics_destroyJoint(entity);
    }

    setRevoluteMotorSpeed(entity: Entity, speed: number): void {
        this.module_._physics_setRevoluteMotorSpeed(entity, speed);
    }

    setRevoluteMaxMotorTorque(entity: Entity, torque: number): void {
        this.module_._physics_setRevoluteMaxMotorTorque(entity, torque);
    }

    enableRevoluteMotor(entity: Entity, enable: boolean): void {
        this.module_._physics_enableRevoluteMotor(entity, enable ? 1 : 0);
    }

    enableRevoluteLimit(entity: Entity, enable: boolean): void {
        this.module_._physics_enableRevoluteLimit(entity, enable ? 1 : 0);
    }

    setRevoluteLimits(entity: Entity, lower: number, upper: number): void {
        this.module_._physics_setRevoluteLimits(entity, lower, upper);
    }

    getRevoluteAngle(entity: Entity): number {
        return this.module_._physics_getRevoluteAngle(entity);
    }

    getRevoluteMotorTorque(entity: Entity): number {
        return this.module_._physics_getRevoluteMotorTorque(entity);
    }

    raycast(
        origin: Vec2, direction: Vec2, maxDistance: number,
        maskBits = 0xFFFF, ppu = this.ppu_,
    ): RaycastHit[] {
        const invPpu = 1 / ppu;
        const count = this.module_._physics_raycast(
            origin.x * invPpu, origin.y * invPpu,
            direction.x, direction.y,
            maxDistance * invPpu, maskBits,
        );
        if (count === 0) return [];

        const ptr = this.module_._physics_getRaycastBuffer() >> 2;
        const results: RaycastHit[] = [];
        for (let i = 0; i < count; i++) {
            const base = ptr + i * CAST_HIT_STRIDE;
            results.push({
                entity: this.module_.HEAPU32[base] as Entity,
                point: { x: this.module_.HEAPF32[base + 1] * ppu, y: this.module_.HEAPF32[base + 2] * ppu },
                normal: { x: this.module_.HEAPF32[base + 3], y: this.module_.HEAPF32[base + 4] },
                fraction: this.module_.HEAPF32[base + 5],
            });
        }
        results.sort((a, b) => a.fraction - b.fraction);
        return results;
    }

    overlapCircle(center: Vec2, radius: number, maskBits = 0xFFFF, ppu = this.ppu_): Entity[] {
        const invPpu = 1 / ppu;
        const count = this.module_._physics_overlapCircle(
            center.x * invPpu, center.y * invPpu,
            radius * invPpu, maskBits,
        );
        return this.readUniqueEntityBuffer_(count);
    }

    setAwake(entity: Entity, awake: boolean): void {
        this.module_._physics_setAwake(entity, awake ? 1 : 0);
    }

    isAwake(entity: Entity): boolean {
        return this.module_._physics_isAwake(entity) !== 0;
    }

    shapeCastCircle(
        center: Vec2, radius: number, translation: Vec2,
        maskBits = 0xFFFF, ppu = this.ppu_,
    ): ShapeCastHit[] {
        const invPpu = 1 / ppu;
        const count = this.module_._physics_shapeCastCircle(
            center.x * invPpu, center.y * invPpu, radius * invPpu,
            translation.x * invPpu, translation.y * invPpu, maskBits,
        );
        return this.readShapeCastBuffer_(count, ppu);
    }

    shapeCastBox(
        center: Vec2, halfExtents: Vec2, angle: number, translation: Vec2,
        maskBits = 0xFFFF, ppu = this.ppu_,
    ): ShapeCastHit[] {
        const invPpu = 1 / ppu;
        const count = this.module_._physics_shapeCastBox(
            center.x * invPpu, center.y * invPpu,
            halfExtents.x * invPpu, halfExtents.y * invPpu, angle,
            translation.x * invPpu, translation.y * invPpu, maskBits,
        );
        return this.readShapeCastBuffer_(count, ppu);
    }

    shapeCastCapsule(
        center1: Vec2, center2: Vec2, radius: number, translation: Vec2,
        maskBits = 0xFFFF, ppu = this.ppu_,
    ): ShapeCastHit[] {
        const invPpu = 1 / ppu;
        const count = this.module_._physics_shapeCastCapsule(
            center1.x * invPpu, center1.y * invPpu,
            center2.x * invPpu, center2.y * invPpu,
            radius * invPpu,
            translation.x * invPpu, translation.y * invPpu, maskBits,
        );
        return this.readShapeCastBuffer_(count, ppu);
    }

    /**
     * Advance a kinematic capsule character one step against the world using Box2D's
     * native mover (collide-into-planes + depenetrating slide). Unlike a raw shape
     * cast this resolves resting/touching contacts with valid normals, so a grounded
     * character slides instead of wedging. Capsule endpoints/radius and `pos`/`velocity`
     * are world pixels; `dt` seconds; `up` a unit vector; `floorCos = cos(floorMaxAngle)`.
     * `self` is excluded from the collision. Returns null if the module isn't ready.
     */
    moveCharacter(
        pos: Vec2, c1: Vec2, c2: Vec2, radius: number,
        velocity: Vec2, dt: number, up: Vec2, floorCos: number,
        maskBits: number, self: Entity,
        skinWidth = 0, maxSlides = 5, snapLength = 0, slideOnCeiling = true,
        ppu = this.ppu_, options: MoverOptions = {},
    ): MoverResult | null {
        const invPpu = 1 / ppu;
        const flags = (options.dropThrough ? 1 : 0) | (options.ignoreDynamic ? 2 : 0)
            | (options.blockSteepSlopes ? 4 : 0) | (options.wasOnFloor ? 8 : 0);
        const ok = this.module_._physics_moveCharacter(
            pos.x * invPpu, pos.y * invPpu,
            c1.x * invPpu, c1.y * invPpu, c2.x * invPpu, c2.y * invPpu, radius * invPpu,
            velocity.x * invPpu, velocity.y * invPpu, dt,
            up.x, up.y, floorCos, maskBits, self >>> 0,
            skinWidth * invPpu, maxSlides, snapLength * invPpu, slideOnCeiling ? 1 : 0,
            (options.carry?.x ?? 0) * invPpu, (options.carry?.y ?? 0) * invPpu, flags, (options.stepHeight ?? 0) * invPpu,
        );
        if (!ok) return null;
        const base = this.module_._physics_getMoveCharacterBuffer() >> 2;
        const h = this.module_.HEAPF32, bits = this.module_.HEAPU32;
        const floor = bits[base + 9]!, hitCount = h[base + 10]!;
        let hits: MoverResult['hits'];
        for (let i = 0; i < hitCount; i++) {
            (hits ??= []).push({ entity: bits[base + 11 + i * 3]! as Entity, normalX: h[base + 12 + i * 3]!, normalY: h[base + 13 + i * 3]! });
        }
        return {
            floorEntity: floor === 0xFFFFFFFF ? null : floor as Entity, hits,
            dx: h[base] * ppu, dy: h[base + 1] * ppu,
            velX: h[base + 2] * ppu, velY: h[base + 3] * ppu,
            isOnFloor: h[base + 4] !== 0, isOnWall: h[base + 5] !== 0, isOnCeiling: h[base + 6] !== 0,
            floorNormalX: h[base + 7], floorNormalY: h[base + 8],
        };
    }

    overlapAABB(min: Vec2, max: Vec2, maskBits = 0xFFFF, ppu = this.ppu_): Entity[] {
        const invPpu = 1 / ppu;
        const count = this.module_._physics_overlapAABB(
            min.x * invPpu, min.y * invPpu,
            max.x * invPpu, max.y * invPpu, maskBits,
        );
        return this.readUniqueEntityBuffer_(count);
    }

    getMass(entity: Entity): number {
        return this.module_._physics_getBodyMass(entity);
    }

    getInertia(entity: Entity): number {
        return this.module_._physics_getBodyInertia(entity);
    }

    getCenterOfMass(entity: Entity, ppu = this.ppu_): Vec2 {
        const ptr = this.module_._physics_getBodyCenterOfMass(entity);
        const base = ptr >> 2;
        return {
            x: this.module_.HEAPF32[base] * ppu,
            y: this.module_.HEAPF32[base + 1] * ppu,
        };
    }

    getMassData(entity: Entity, ppu = this.ppu_): MassData {
        return {
            mass: this.getMass(entity),
            inertia: this.getInertia(entity),
            centerOfMass: this.getCenterOfMass(entity, ppu),
        };
    }

    getDistanceJointLength(entity: Entity, ppu = this.ppu_): number {
        return this.module_._physics_getDistanceJointLength(entity) * ppu;
    }

    getDistanceJointCurrentLength(entity: Entity, ppu = this.ppu_): number {
        return this.module_._physics_getDistanceJointCurrentLength(entity) * ppu;
    }

    setDistanceJointLength(entity: Entity, length: number, ppu = this.ppu_): void {
        this.module_._physics_setDistanceJointLength(entity, length / ppu);
    }

    enableDistanceJointSpring(entity: Entity, enable: boolean): void {
        this.module_._physics_enableDistanceJointSpring(entity, enable ? 1 : 0);
    }

    enableDistanceJointLimit(entity: Entity, enable: boolean): void {
        this.module_._physics_enableDistanceJointLimit(entity, enable ? 1 : 0);
    }

    setDistanceJointLimits(entity: Entity, minLength: number, maxLength: number, ppu = this.ppu_): void {
        this.module_._physics_setDistanceJointLimits(entity, minLength / ppu, maxLength / ppu);
    }

    enableDistanceJointMotor(entity: Entity, enable: boolean): void {
        this.module_._physics_enableDistanceJointMotor(entity, enable ? 1 : 0);
    }

    setDistanceJointMotorSpeed(entity: Entity, speed: number): void {
        this.module_._physics_setDistanceJointMotorSpeed(entity, speed);
    }

    setDistanceJointMaxMotorForce(entity: Entity, force: number): void {
        this.module_._physics_setDistanceJointMaxMotorForce(entity, force);
    }

    getDistanceJointMotorForce(entity: Entity): number {
        return this.module_._physics_getDistanceJointMotorForce(entity);
    }

    getPrismaticJointTranslation(entity: Entity, ppu = this.ppu_): number {
        return this.module_._physics_getPrismaticJointTranslation(entity) * ppu;
    }

    getPrismaticJointSpeed(entity: Entity, ppu = this.ppu_): number {
        return this.module_._physics_getPrismaticJointSpeed(entity) * ppu;
    }

    enablePrismaticJointSpring(entity: Entity, enable: boolean): void {
        this.module_._physics_enablePrismaticJointSpring(entity, enable ? 1 : 0);
    }

    enablePrismaticJointLimit(entity: Entity, enable: boolean): void {
        this.module_._physics_enablePrismaticJointLimit(entity, enable ? 1 : 0);
    }

    setPrismaticJointLimits(entity: Entity, lower: number, upper: number, ppu = this.ppu_): void {
        this.module_._physics_setPrismaticJointLimits(entity, lower / ppu, upper / ppu);
    }

    enablePrismaticJointMotor(entity: Entity, enable: boolean): void {
        this.module_._physics_enablePrismaticJointMotor(entity, enable ? 1 : 0);
    }

    setPrismaticJointMotorSpeed(entity: Entity, speed: number): void {
        this.module_._physics_setPrismaticJointMotorSpeed(entity, speed);
    }

    setPrismaticJointMaxMotorForce(entity: Entity, force: number): void {
        this.module_._physics_setPrismaticJointMaxMotorForce(entity, force);
    }

    getPrismaticJointMotorForce(entity: Entity): number {
        return this.module_._physics_getPrismaticJointMotorForce(entity);
    }

    enableWheelJointSpring(entity: Entity, enable: boolean): void {
        this.module_._physics_enableWheelJointSpring(entity, enable ? 1 : 0);
    }

    enableWheelJointLimit(entity: Entity, enable: boolean): void {
        this.module_._physics_enableWheelJointLimit(entity, enable ? 1 : 0);
    }

    setWheelJointLimits(entity: Entity, lower: number, upper: number, ppu = this.ppu_): void {
        this.module_._physics_setWheelJointLimits(entity, lower / ppu, upper / ppu);
    }

    enableWheelJointMotor(entity: Entity, enable: boolean): void {
        this.module_._physics_enableWheelJointMotor(entity, enable ? 1 : 0);
    }

    setWheelJointMotorSpeed(entity: Entity, speed: number): void {
        this.module_._physics_setWheelJointMotorSpeed(entity, speed);
    }

    setWheelJointMaxMotorTorque(entity: Entity, torque: number): void {
        this.module_._physics_setWheelJointMaxMotorTorque(entity, torque);
    }

    getWheelJointMotorTorque(entity: Entity): number {
        return this.module_._physics_getWheelJointMotorTorque(entity);
    }

    // ── Motor joint (runtime control) ───────────────────────────────────────
    // `velocity` is world pixels/s (scaled to meters); force/torque are physics-space
    // (newtons, N·m). Targets a joint keyed by its owning entity (see MotorJoint2D).

    setMotorJointLinearVelocity(entity: Entity, velocity: Vec2, ppu = this.ppu_): void {
        this.module_._physics_setMotorJointLinearVelocity(entity, velocity.x / ppu, velocity.y / ppu);
    }

    setMotorJointAngularVelocity(entity: Entity, omega: number): void {
        this.module_._physics_setMotorJointAngularVelocity(entity, omega);
    }

    setMotorJointMaxVelocityForce(entity: Entity, force: number): void {
        this.module_._physics_setMotorJointMaxVelocityForce(entity, force);
    }

    setMotorJointMaxVelocityTorque(entity: Entity, torque: number): void {
        this.module_._physics_setMotorJointMaxVelocityTorque(entity, torque);
    }

    // ── Mouse / drag joint ──────────────────────────────────────────────────
    // Box2D v3 has no dedicated mouse joint; this is the canonical replacement — a
    // kinematic body plus a spring motor joint that pulls `entity` toward a
    // world-pixel target. Create on pointer-down, setMouseTarget on move, destroy on
    // up. Only one drag is live at a time (a new create replaces the previous).
    // `maxForce` defaults to an auto-sized value from the body's weight.

    createMouseJoint(
        entity: Entity,
        target: Vec2,
        opts: { hertz?: number; dampingRatio?: number; maxForce?: number } = {},
        ppu = this.ppu_,
    ): boolean {
        return this.module_._physics_createMouseJoint(
            entity, target.x / ppu, target.y / ppu,
            opts.hertz ?? 7.5, opts.dampingRatio ?? 1.0, opts.maxForce ?? 0,
        ) !== 0;
    }

    setMouseTarget(target: Vec2, ppu = this.ppu_): void {
        this.module_._physics_setMouseTarget(target.x / ppu, target.y / ppu);
    }

    destroyMouseJoint(): void {
        this.module_._physics_destroyMouseJoint();
    }

    hasMouseJoint(): boolean {
        return this.module_._physics_hasMouseJoint() !== 0;
    }

    private readUniqueEntityBuffer_(count: number): Entity[] {
        if (count === 0) return [];
        const ptr = this.module_._physics_getOverlapBuffer() >> 2;
        const results: Entity[] = [];
        const seen = new Set<number>();
        for (let i = 0; i < count; i++) {
            const entityId = this.module_.HEAPU32[ptr + i] as Entity;
            if (!seen.has(entityId)) {
                seen.add(entityId);
                results.push(entityId);
            }
        }
        return results;
    }

    private readShapeCastBuffer_(count: number, ppu: number): ShapeCastHit[] {
        if (count === 0) return [];
        const ptr = this.module_._physics_getShapeCastBuffer() >> 2;
        const results: ShapeCastHit[] = [];
        for (let i = 0; i < count; i++) {
            const base = ptr + i * CAST_HIT_STRIDE;
            results.push({
                entity: this.module_.HEAPU32[base] as Entity,
                point: { x: this.module_.HEAPF32[base + 1] * ppu, y: this.module_.HEAPF32[base + 2] * ppu },
                normal: { x: this.module_.HEAPF32[base + 3], y: this.module_.HEAPF32[base + 4] },
                fraction: this.module_.HEAPF32[base + 5],
            });
        }
        results.sort((a, b) => a.fraction - b.fraction);
        return results;
    }

    static setDebugDraw(app: App, enabled: boolean): void {
        const config = app.getResource<Physics2DDebugDrawConfig>(Physics2DDebugDraw);
        if (config) {
            config.enabled = enabled;
            app.insertResource(Physics2DDebugDraw, config);
        }
    }

    static setDebugDrawConfig(app: App, config: Partial<Physics2DDebugDrawConfig>): void {
        const current = app.getResource<Physics2DDebugDrawConfig>(Physics2DDebugDraw);
        if (current) {
            app.insertResource(Physics2DDebugDraw, { ...current, ...config });
        }
    }
}

/**
 * Resource published by `Physics2DPlugin` once the wasm module is ready.
 * Game code reads it as `Res(Physics)` / `app.getResource(Physics)` to call forces,
 * impulses, joint helpers, raycasts, etc.
 */
/**
 * The physics world, as `Res(Physics)` hands it over — queries, impulses and the
 * step's own knobs. Bodies and colliders are components; this is for what has no
 * component to be.
 *
 * `@beta`: the corpus reaches three of thirty-seven physics symbols, so the
 * vocabulary is settled well ahead of the evidence for it.
 *
 * @beta
 */
export const Physics2D = defineResource<Physics2DAPI>(null!, 'Physics2D');