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.

4.2 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
#pragma once

// The module's entry points are marked KEEPALIVE so the emscripten link keeps them
// exported. A native build compiles the same TUs into the host binary, where the
// attribute has no meaning and the header does not exist.
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#else
#define EMSCRIPTEN_KEEPALIVE
#endif

#include <box2d/box2d.h>

#include <unordered_map>
#include <vector>
#include <cstdint>
#include <cstring>

static constexpr int MAX_PHYSICS_STEPS_PER_FRAME = 8;
static constexpr int RAYCAST_STRIDE = 6;
static constexpr int MAX_RAYCAST_HITS = 64;
static constexpr int MAX_OVERLAP_HITS = 64;
static constexpr int SHAPECAST_STRIDE = 6;

struct PhysicsContext {
    b2WorldId worldId = b2_nullWorldId;
    float fixedTimestep = 1.0f / 60.0f;
    int subStepCount = 4;
    float accumulator = 0.0f;

    std::unordered_map<uint32_t, b2BodyId> entityToBody;
    std::unordered_map<uint32_t, std::vector<b2ShapeId>> entityToShapes;
    std::unordered_map<uint32_t, b2JointId> entityToJoint;
    std::vector<uint32_t> dynamicBodyEntities;

    // Box2D discards solver velocity when a body moves to the disabled set.
    struct PausedMotion {
        b2Vec2 linearVelocity;
        float angularVelocity;
    };
    std::unordered_map<uint32_t, PausedMotion> pausedMotion;

    // One-way platforms: entity -> normalized solid-side normal and coordinate frame.
    // Read by the pre-solve callback to cancel contacts that approach
    // from the pass-through side. Empty map = zero pre-solve overhead.
    struct OneWayNormal {
        b2Vec2 normal;
        bool localSpace = false;
    };
    std::unordered_map<uint32_t, OneWayNormal> oneWayNormals;

    // Interactive drag: a single kinematic "mouse body" + motor joint pulling one
    // target body toward the cursor (Box2D v3 has no dedicated mouse joint).
    b2BodyId mouseBodyId = b2_nullBodyId;
    b2JointId mouseJointId = b2_nullJointId;

    std::vector<float> dynamicTransformBuffer;

    // Render interpolation, kept here rather than in JS: the two most recent
    // fixed-step poses and the lerped result, all in the same flat
    // [entityBits, x, y, angle] layout the readback hands out. A per-body object
    // graph on the JS side would put a 5000-iteration hot loop on the every-frame
    // path, which the no-JIT budget forbids (docs/REARCH_NATIVE.md §3.2).
    std::vector<float> posePrev;
    std::vector<float> poseCur;
    std::vector<float> poseInterpolated;
    // Maps entity -> index into posePrev, built lazily and only when the body set
    // changed between the two snapshots; steady state matches by position instead.
    std::unordered_map<uint32_t, uint32_t> posePrevIndex;

    std::vector<float> collisionEnterBuffer;
    std::vector<float> collisionExitBuffer;
    std::vector<float> sensorEnterBuffer;
    std::vector<float> sensorExitBuffer;
    std::vector<float> hitEventBuffer;

    float velocityBuffer[2] = {};
    float gravityBuffer[2] = {};

    void reset() {
        entityToBody.clear();
        entityToShapes.clear();
        entityToJoint.clear();
        pausedMotion.clear();
        oneWayNormals.clear();
        mouseBodyId = b2_nullBodyId;
        mouseJointId = b2_nullJointId;
        dynamicBodyEntities.clear();
        dynamicTransformBuffer.clear();
        posePrev.clear();
        poseCur.clear();
        poseInterpolated.clear();
        posePrevIndex.clear();
        collisionEnterBuffer.clear();
        collisionExitBuffer.clear();
        sensorEnterBuffer.clear();
        sensorExitBuffer.clear();
        hitEventBuffer.clear();
        accumulator = 0.0f;

        if (b2World_IsValid(worldId)) {
            b2DestroyWorld(worldId);
        }
        worldId = b2_nullWorldId;
    }
};

extern PhysicsContext g_ctx;

extern std::vector<float> g_raycastBuffer;
extern std::vector<float> g_overlapBuffer;
extern std::vector<float> g_shapeCastBuffer;
extern float g_massDataBuffer[2];

b2BodyId findValidBody(uint32_t entityId);
b2JointId findValidJoint(uint32_t entityId);
uint32_t entityFromBody(b2BodyId bodyId);
uint32_t entityFromShape(b2ShapeId shapeId);
void pushEntityBits(std::vector<float>& buf, uint32_t entityId);