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.

feat(physics): a 3D body drives its entity's Transform

esengine8e668183fed5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8998a9548..5dc9bcd3b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,23 @@ published separately; it ships inside the editor.
### Added
+- **A 3D physics world, beside the 2D one rather than over it.** Jolt Physics
+ ships as a second side module, so a project that never asks for a 3D world
+ never pays the 1.2MB it weighs — and a 2D scene keeps the solver, the units
+ and the feel it already has. `RigidBody3D` with a `BoxCollider3D`,
+ `SphereCollider3D` or `CapsuleCollider3D` puts an entity under it, and what
+ the solver moves is written back to its `Transform`.
+
+ Sizes are authored in world units and reach the solver in metres, at the same
+ `pixelsPerUnit` the 2D world uses: a solver tuned for metres behaves nothing
+ like itself when a character is 180 units tall.
+
+ Two things emscripten does not give for free, both of which present as
+ something other than themselves. Jolt DECLARES that it uses SSE4.1 under wasm
+ SIMD, so those intrinsics have to be asked for or the library will not compile
+ at all; and its solver needs far more stack than the 64KB default, which a
+ short stack reports as an out-of-bounds access inside the step.
+
- **A panorama becomes an environment, and an ambient light casts it.** An
equirectangular `.hdr` in a project now bakes into the two things a renderer
asks an environment for, and an `Ambient` `Light2D` can point at the result:
diff --git a/CMakeLists.txt b/CMakeLists.txt
index b43242f5e..332715d40 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -177,6 +177,7 @@ endif()
list(APPEND ESENGINE_HEADERS
src/esengine/ecs/components/RigidBody.hpp
src/esengine/ecs/components/Collider.hpp
+ src/esengine/ecs/components/RigidBody3D.hpp
)
set(GENERATED_WEB_BINDINGS "${CMAKE_CURRENT_SOURCE_DIR}/src/esengine/bindings/WebBindings.generated.cpp")
diff --git a/desktop/src/engine/componentDocs.generated.ts b/desktop/src/engine/componentDocs.generated.ts
index 40b67a9ba..2344e494e 100644
--- a/desktop/src/engine/componentDocs.generated.ts
+++ b/desktop/src/engine/componentDocs.generated.ts
@@ -10,11 +10,13 @@ export const COMPONENT_DOC_PATHS: Readonly<Record<string, string>> = {
BehaviorTreeAgent: 'reference/components/gameplay/#behaviortreeagent',
BitmapText: 'reference/components/graphics/#bitmaptext',
BoxCollider: 'reference/components/physics/#boxcollider',
+ BoxCollider3D: 'reference/components/physics/#boxcollider3d',
CacheAsBitmap: 'reference/components/graphics/#cacheasbitmap',
Camera: 'reference/components/graphics/#camera',
CameraBounds: 'reference/components/graphics/#camerabounds',
Canvas: 'reference/components/graphics/#canvas',
CapsuleCollider: 'reference/components/physics/#capsulecollider',
+ CapsuleCollider3D: 'reference/components/physics/#capsulecollider3d',
ChainCollider: 'reference/components/physics/#chaincollider',
CharacterController: 'reference/components/physics/#charactercontroller',
Children: 'reference/components/core/#children',
@@ -50,12 +52,14 @@ export const COMPONENT_DOC_PATHS: Readonly<Record<string, string>> = {
Replicated: 'reference/components/gameplay/#replicated',
RevoluteJoint: 'reference/components/physics/#revolutejoint',
RigidBody: 'reference/components/physics/#rigidbody',
+ RigidBody3D: 'reference/components/physics/#rigidbody3d',
RuntimeOnly: 'reference/components/core/#runtimeonly',
SafeArea: 'reference/components/ui/#safearea',
SceneOwner: 'reference/components/core/#sceneowner',
SegmentCollider: 'reference/components/physics/#segmentcollider',
ShadowCaster2D: 'reference/components/graphics/#shadowcaster2d',
ShapeRenderer: 'reference/components/graphics/#shaperenderer',
+ SphereCollider3D: 'reference/components/physics/#spherecollider3d',
SpineAnimation: 'reference/components/animation/#spineanimation',
Sprite: 'reference/components/graphics/#sprite',
SpriteAnimator: 'reference/components/animation/#spriteanimator',
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index 83f5bd353..eb1812cfc 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -242,6 +242,7 @@ export default defineConfig({
collapsed: true,
items: [
{ label: 'Physics', translations: { 'zh-CN': '物理' }, slug: 'gameplay/physics' },
+ { label: '3D Physics', translations: { 'zh-CN': '3D 物理' }, slug: 'gameplay/physics-3d' },
{ label: 'Markers & Trigger Areas', translations: { 'zh-CN': '标记与触发区' }, slug: 'gameplay/markers' },
{
label: 'Gameplay AI',
diff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
new file mode 100644
index 000000000..389f61096
--- /dev/null
+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx
@@ -0,0 +1,55 @@
+---
+title: 3D Physics
+description: The 3D rigid-body world — Jolt-backed bodies, box/sphere/capsule shapes, and how it sits beside the 2D physics rather than replacing it.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+A 3D model can be imported, animated, skinned and lit. This is what makes it stand
+somewhere: a rigid-body world powered by **Jolt Physics**, running in its own
+WebAssembly module.
+
+It sits **beside** the [2D physics](/docs/gameplay/physics/), not on top of it. A 2D
+scene keeps the solver, the units and the feel it already has, and a project that
+never asks for a 3D world never loads it.
+
+## Bodies
+
+An entity is in the world when it carries a `RigidBody3D` **and** a shape. A body
+with no shape has no extent to collide with, so it is left out entirely rather than
+falling forever as an invisible point.
+
+```typescript
+cmds.spawn()
+ .insert(Transform, { position: { x: 0, y: 400, z: 0 } })
+ .insert(RigidBody3D, { bodyType: BodyType.Dynamic })
+ .insert(CapsuleCollider3D, { radius: 30, halfHeight: 50 });
+```
+
+| Field | What it does |
+|---|---|
+| `bodyType` | `Static` never moves, `Kinematic` is moved by hand, `Dynamic` is solved. |
+| `gravityScale` | This body's share of world gravity. `0` is weightlessness, not slow falling. |
+| `linearDamping` / `angularDamping` | How quickly motion bleeds off. |
+| `fixedRotation` | Freezes the orientation the body was given — what keeps a character from toppling. It does not right a body that starts tilted. |
+
+## Shapes
+
+| Component | Extent |
+|---|---|
+| `BoxCollider3D` | `halfExtents` on each axis. |
+| `SphereCollider3D` | `radius`. |
+| `CapsuleCollider3D` | An upright capsule: `halfHeight` is the cylinder's half, with a cap of `radius` on each end, so the total height is `2 * (halfHeight + radius)`. |
+
+<Aside>
+ Sizes are authored in **world units** and reach the solver in metres, at the same
+ `pixelsPerUnit` the 2D world uses (100 by default). A solver tuned for metres
+ behaves nothing like itself when a character is 180 units tall, so the conversion
+ is not optional — it is why a capsule 60 units wide falls the way a person does.
+</Aside>
+
+## Which world a scene is in
+
+Nothing stops an entity carrying both sets, but nothing merges them either: the two
+worlds do not see each other, and a 2D collider will never stop a 3D body. Pick one
+per scene.
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
new file mode 100644
index 000000000..927343cc0
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx
@@ -0,0 +1,50 @@
+---
+title: 3D 物理
+description: 3D 刚体世界——基于 Jolt 的刚体、盒/球/胶囊形状,以及它为什么是与 2D 物理并存而不是取代它。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+一个 3D 模型已经能导入、能动、能变形、能被照亮。这一页讲的是让它**站在某处**:
+一个由 **Jolt Physics** 驱动的刚体世界,跑在它自己的 WebAssembly 模块里。
+
+它与 [2D 物理](/docs/zh-cn/gameplay/physics/)**并存**,不是取代:2D 场景保留它已经有的
+求解器、单位和手感,而一个从不索取 3D 世界的项目也从不加载它。
+
+## 刚体
+
+一个实体同时带着 `RigidBody3D` **和**一个形状时才在世界里。没有形状的刚体没有任何
+广延可供碰撞,所以它干脆不被注册——而不是变成一个永远下落的隐形点。
+
+```typescript
+cmds.spawn()
+ .insert(Transform, { position: { x: 0, y: 400, z: 0 } })
+ .insert(RigidBody3D, { bodyType: BodyType.Dynamic })
+ .insert(CapsuleCollider3D, { radius: 30, halfHeight: 50 });
+```
+
+| 字段 | 作用 |
+|---|---|
+| `bodyType` | `Static` 从不移动,`Kinematic` 由你搬动,`Dynamic` 由求解器解。 |
+| `gravityScale` | 这个刚体分担的重力比例。`0` 是失重,不是「掉得慢」。 |
+| `linearDamping` / `angularDamping` | 运动衰减的快慢。 |
+| `fixedRotation` | 冻结刚体被给定的朝向——让角色不会倒下的那个开关。它不会把一个一开始就歪的刚体扶正。 |
+
+## 形状
+
+| 组件 | 广延 |
+|---|---|
+| `BoxCollider3D` | 每个轴上的 `halfExtents`。 |
+| `SphereCollider3D` | `radius`。 |
+| `CapsuleCollider3D` | 一个直立胶囊:`halfHeight` 是圆柱段的一半,两端各扣一个 `radius` 的半球,所以总高是 `2 * (halfHeight + radius)`。 |
+
+<Aside>
+ 尺寸按**世界单位**书写,以米为单位抵达求解器,用的是 2D 世界同一个 `pixelsPerUnit`
+ (默认 100)。一个按米调好的求解器在角色高 180 单位时完全不是它自己,所以这次换算
+ 不是可选项——它正是一个 60 单位宽的胶囊会像人一样倒下的原因。
+</Aside>
+
+## 一个场景在哪个世界里
+
+没有东西阻止一个实体同时带两套组件,但也没有东西会把它们合并:两个世界互相看不见,
+一个 2D 碰撞体永远拦不住一个 3D 刚体。**一个场景选一套。**
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index f27651f0e..74ba9e7f3 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -107,6 +107,10 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
SegmentCollider: { category: 'physics', summary: 'A single line segment — a one-sided wall or edge.', doc: 'gameplay/physics', anchor: 'colliders', anchorZh: '碰撞体' },
PolygonCollider: { category: 'physics', summary: 'A convex polygon collision shape from your own points.', doc: 'gameplay/physics', anchor: 'colliders', anchorZh: '碰撞体' },
ChainCollider: { category: 'physics', summary: 'A polyline of edges — open or looped — for static terrain.', doc: 'gameplay/physics', anchor: 'colliders', anchorZh: '碰撞体' },
+ RigidBody3D: { category: 'physics', summary: 'Puts the entity under the 3D solver — its own component set, so a 2D scene keeps the world it already has.', doc: 'gameplay/physics-3d', anchor: 'bodies', anchorZh: 'bodies' },
+ BoxCollider3D: { category: 'physics', summary: 'A box collision shape in 3D. Half-extents are in world units.', doc: 'gameplay/physics-3d', anchor: 'shapes', anchorZh: 'shapes' },
+ SphereCollider3D: { category: 'physics', summary: 'A sphere collision shape in 3D.', doc: 'gameplay/physics-3d', anchor: 'shapes', anchorZh: 'shapes' },
+ CapsuleCollider3D: { category: 'physics', summary: 'An upright capsule — what a 3D character is. Total height is 2*(halfHeight + radius).', doc: 'gameplay/physics-3d', anchor: 'shapes', anchorZh: 'shapes' },
CharacterController: { category: 'physics', summary: 'Kinematic character movement that slides along walls, climbs slopes and reports ground contact.', doc: 'gameplay/physics', anchor: 'character-controller', anchorZh: '角色控制器' },
OneWayPlatform: { category: 'physics', summary: 'Makes a collider solid from one side only, so a body passes up through it and lands on top.', doc: 'gameplay/physics', anchor: 'one-way-platforms', anchorZh: '单向平台' },
DistanceJoint: { category: 'physics', summary: 'Holds two bodies a fixed (or spring-limited) distance apart.', doc: 'gameplay/physics', anchor: 'joints', anchorZh: '关节' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index eb9a61499..70ede4eb6 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -256,6 +256,39 @@
}
]
},
+ {
+ "name": "BoxCollider3D",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "halfExtents",
+ "type": "Vec3",
+ "default": "(0.5, 0.5, 0.5)"
+ },
+ {
+ "key": "friction",
+ "type": "number",
+ "default": "0.3",
+ "range": "≥ 0"
+ },
+ {
+ "key": "restitution",
+ "type": "number",
+ "default": "0",
+ "range": "0–1"
+ },
+ {
+ "key": "isSensor",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ]
+ },
{
"name": "CacheAsBitmap",
"source": "ts",
@@ -521,6 +554,46 @@
}
]
},
+ {
+ "name": "CapsuleCollider3D",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "radius",
+ "type": "number",
+ "default": "0.3",
+ "range": "≥ 0"
+ },
+ {
+ "key": "halfHeight",
+ "type": "number",
+ "default": "0.5",
+ "range": "≥ 0"
+ },
+ {
+ "key": "friction",
+ "type": "number",
+ "default": "0.3",
+ "range": "≥ 0"
+ },
+ {
+ "key": "restitution",
+ "type": "number",
+ "default": "0",
+ "range": "0–1"
+ },
+ {
+ "key": "isSensor",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ]
+ },
{
"name": "ChainCollider",
"source": "ts",
@@ -2423,6 +2496,50 @@
}
]
},
+ {
+ "name": "RigidBody3D",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "bodyType",
+ "type": "enum",
+ "default": "Dynamic",
+ "values": [
+ "Static",
+ "Kinematic",
+ "Dynamic"
+ ]
+ },
+ {
+ "key": "gravityScale",
+ "type": "number",
+ "default": "1",
+ "range": "≥ 0"
+ },
+ {
+ "key": "linearDamping",
+ "type": "number",
+ "default": "0.05",
+ "range": "≥ 0"
+ },
+ {
+ "key": "angularDamping",
+ "type": "number",
+ "default": "0.05",
+ "range": "≥ 0"
+ },
+ {
+ "key": "fixedRotation",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ]
+ },
{
"name": "RuntimeOnly",
"source": "ts",
@@ -2596,6 +2713,40 @@
}
]
},
+ {
+ "name": "SphereCollider3D",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "radius",
+ "type": "number",
+ "default": "0.5",
+ "range": "≥ 0"
+ },
+ {
+ "key": "friction",
+ "type": "number",
+ "default": "0.3",
+ "range": "≥ 0"
+ },
+ {
+ "key": "restitution",
+ "type": "number",
+ "default": "0",
+ "range": "0–1"
+ },
+ {
+ "key": "isSensor",
+ "type": "boolean",
+ "default": "false"
+ },
+ {
+ "key": "enabled",
+ "type": "boolean",
+ "default": "true"
+ }
+ ]
+ },
{
"name": "SpineAnimation",
"source": "cpp",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 1e9b6c007..6e28da56e 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5,7 +5,7 @@ Symbols: 113 public · 58 beta · 1418 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"65f6ac377586cd75"
+"fb8d63de6b3e9865"
```
## ANCHOR_AXES — const @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 42f2e5419..02d53d206 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5,7 +5,7 @@ Symbols: 113 public · 63 beta · 1437 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"65f6ac377586cd75"
+"fb8d63de6b3e9865"
```
## ANCHOR_AXES — const @experimental
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 96e9a9abf..a7519deb6 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -14,9 +14,11 @@ shutdown: () => void
## CppRegistry — interface @experimental
```
addBitmapText: (entity: Entity, component: BitmapText) => void
+addBoxCollider3D: (entity: Entity, component: BoxCollider3D) => void
addBoxCollider: (entity: Entity, component: BoxCollider) => void
addCamera: (entity: Entity, component: Camera) => void
addCanvas: (entity: Entity, component: Canvas) => void
+addCapsuleCollider3D: (entity: Entity, component: CapsuleCollider3D) => void
addCapsuleCollider: (entity: Entity, component: CapsuleCollider) => void
addChildren: (entity: Entity, component: Children) => void
addCircleCollider: (entity: Entity, component: CircleCollider) => void
@@ -29,10 +31,12 @@ addMeshSkin: (entity: Entity, component: MeshSkin) => void
addParent: (entity: Entity, component: Parent) => void
addParticleEmitter: (entity: Entity, component: ParticleEmitter) => void
addParticleForceField: (entity: Entity, component: ParticleForceField) => void
+addRigidBody3D: (entity: Entity, component: RigidBody3D) => void
addRigidBody: (entity: Entity, component: RigidBody) => void
addSegmentCollider: (entity: Entity, component: SegmentCollider) => void
addShadowCaster2D: (entity: Entity, component: ShadowCaster2D) => void
addShapeRenderer: (entity: Entity, component: ShapeRenderer) => void
+addSphereCollider3D: (entity: Entity, component: SphereCollider3D) => void
addSpineAnimation: (entity: Entity, component: SpineAnimation) => void
addSprite: (entity: Entity, component: Sprite) => void
addTilemapLayer: (entity: Entity, component: TilemapLayer) => void
@@ -49,9 +53,11 @@ delete: () => void
destroy: (entity: Entity) => void
entityCount: () => number
getBitmapText: (entity: Entity) => BitmapText
+getBoxCollider3D: (entity: Entity) => BoxCollider3D
getBoxCollider: (entity: Entity) => BoxCollider
getCamera: (entity: Entity) => Camera
getCanvas: (entity: Entity) => Canvas
+getCapsuleCollider3D: (entity: Entity) => CapsuleCollider3D
getCapsuleCollider: (entity: Entity) => CapsuleCollider
getChildren: (entity: Entity) => Children
getCircleCollider: (entity: Entity) => CircleCollider
@@ -64,10 +70,12 @@ getMeshSkin: (entity: Entity) => MeshSkin
getParent: (entity: Entity) => Parent
getParticleEmitter: (entity: Entity) => ParticleEmitter
getParticleForceField: (entity: Entity) => ParticleForceField
+getRigidBody3D: (entity: Entity) => RigidBody3D
getRigidBody: (entity: Entity) => RigidBody
getSegmentCollider: (entity: Entity) => SegmentCollider
getShadowCaster2D: (entity: Entity) => ShadowCaster2D
getShapeRenderer: (entity: Entity) => ShapeRenderer
+getSphereCollider3D: (entity: Entity) => SphereCollider3D
getSpineAnimation: (entity: Entity) => SpineAnimation
getSprite: (entity: Entity) => Sprite
getTilemapLayer: (entity: Entity) => TilemapLayer
@@ -80,9 +88,11 @@ getUIScroll: (entity: Entity) => UIScroll
getUIVisual: (entity: Entity) => UIVisual
getVelocity: (entity: Entity) => Velocity
hasBitmapText: (entity: Entity) => boolean
+hasBoxCollider3D: (entity: Entity) => boolean
hasBoxCollider: (entity: Entity) => boolean
hasCamera: (entity: Entity) => boolean
hasCanvas: (entity: Entity) => boolean
+hasCapsuleCollider3D: (entity: Entity) => boolean
hasCapsuleCollider: (entity: Entity) => boolean
hasChildren: (entity: Entity) => boolean
hasCircleCollider: (entity: Entity) => boolean
@@ -95,10 +105,12 @@ hasMeshSkin: (entity: Entity) => boolean
hasParent: (entity: Entity) => boolean
hasParticleEmitter: (entity: Entity) => boolean
hasParticleForceField: (entity: Entity) => boolean
+hasRigidBody3D: (entity: Entity) => boolean
hasRigidBody: (entity: Entity) => boolean
hasSegmentCollider: (entity: Entity) => boolean
hasShadowCaster2D: (entity: Entity) => boolean
hasShapeRenderer: (entity: Entity) => boolean
+hasSphereCollider3D: (entity: Entity) => boolean
hasSpineAnimation: (entity: Entity) => boolean
hasSprite: (entity: Entity) => boolean
hasTilemapLayer: (entity: Entity) => boolean
@@ -111,9 +123,11 @@ hasUIScroll: (entity: Entity) => boolean
hasUIVisual: (entity: Entity) => boolean
hasVelocity: (entity: Entity) => boolean
removeBitmapText: (entity: Entity) => void
+removeBoxCollider3D: (entity: Entity) => void
removeBoxCollider: (entity: Entity) => void
removeCamera: (entity: Entity) => void
removeCanvas: (entity: Entity) => void
+removeCapsuleCollider3D: (entity: Entity) => void
removeCapsuleCollider: (entity: Entity) => void
removeChildren: (entity: Entity) => void
removeCircleCollider: (entity: Entity) => void
@@ -126,10 +140,12 @@ removeMeshSkin: (entity: Entity) => void
removeParent: (entity: Entity) => void
removeParticleEmitter: (entity: Entity) => void
removeParticleForceField: (entity: Entity) => void
+removeRigidBody3D: (entity: Entity) => void
removeRigidBody: (entity: Entity) => void
removeSegmentCollider: (entity: Entity) => void
removeShadowCaster2D: (entity: Entity) => void
removeShapeRenderer: (entity: Entity) => void
+removeSphereCollider3D: (entity: Entity) => void
removeSpineAnimation: (entity: Entity) => void
removeSprite: (entity: Entity) => void
removeTilemapLayer: (entity: Entity) => void
diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
index 41930b457..c10f0d0b9 100644
--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
@@ -117,6 +117,46 @@ export function createBoxColliderData(): BoxColliderPtrData {
};
}
+export interface BoxCollider3DPtrData {
+ halfExtents: Vec3;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+}
+
+export function fillBoxCollider3D(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: BoxCollider3DPtrData,
+): void {
+ const halfExtents_ = out.halfExtents; halfExtents_.x = f32[ptr >> 2]; halfExtents_.y = f32[(ptr >> 2) + 1]; halfExtents_.z = f32[(ptr >> 2) + 2];
+ out.friction = f32[(ptr + 12) >> 2];
+ out.restitution = f32[(ptr + 16) >> 2];
+ out.isSensor = u8[ptr + 20] !== 0;
+ out.enabled = u8[ptr + 21] !== 0;
+}
+
+export function writeBoxCollider3D(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: BoxCollider3DPtrData,
+): void {
+ f32[ptr >> 2] = data.halfExtents.x; f32[(ptr >> 2) + 1] = data.halfExtents.y; f32[(ptr >> 2) + 2] = data.halfExtents.z;
+ f32[(ptr + 12) >> 2] = data.friction;
+ f32[(ptr + 16) >> 2] = data.restitution;
+ u8[ptr + 20] = data.isSensor ? 1 : 0;
+ u8[ptr + 21] = data.enabled ? 1 : 0;
+}
+
+export function createBoxCollider3DData(): BoxCollider3DPtrData {
+ return {
+ halfExtents: { x: 0, y: 0, z: 0 },
+ friction: 0,
+ restitution: 0,
+ isSensor: false,
+ enabled: false,
+ };
+}
+
export interface CameraPtrData {
projectionType: number;
fov: number;
@@ -289,6 +329,50 @@ export function createCapsuleColliderData(): CapsuleColliderPtrData {
};
}
+export interface CapsuleCollider3DPtrData {
+ radius: number;
+ halfHeight: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+}
+
+export function fillCapsuleCollider3D(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: CapsuleCollider3DPtrData,
+): void {
+ out.radius = f32[ptr >> 2];
+ out.halfHeight = f32[(ptr + 4) >> 2];
+ out.friction = f32[(ptr + 8) >> 2];
+ out.restitution = f32[(ptr + 12) >> 2];
+ out.isSensor = u8[ptr + 16] !== 0;
+ out.enabled = u8[ptr + 17] !== 0;
+}
+
+export function writeCapsuleCollider3D(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: CapsuleCollider3DPtrData,
+): void {
+ f32[ptr >> 2] = data.radius;
+ f32[(ptr + 4) >> 2] = data.halfHeight;
+ f32[(ptr + 8) >> 2] = data.friction;
+ f32[(ptr + 12) >> 2] = data.restitution;
+ u8[ptr + 16] = data.isSensor ? 1 : 0;
+ u8[ptr + 17] = data.enabled ? 1 : 0;
+}
+
+export function createCapsuleCollider3DData(): CapsuleCollider3DPtrData {
+ return {
+ radius: 0,
+ halfHeight: 0,
+ friction: 0,
+ restitution: 0,
+ isSensor: false,
+ enabled: false,
+ };
+}
+
export interface CircleColliderPtrData {
radius: number;
offset: Vec2;
@@ -969,6 +1053,50 @@ export function createRigidBodyData(): RigidBodyPtrData {
};
}
+export interface RigidBody3DPtrData {
+ bodyType: number;
+ gravityScale: number;
+ linearDamping: number;
+ angularDamping: number;
+ fixedRotation: boolean;
+ enabled: boolean;
+}
+
+export function fillRigidBody3D(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: RigidBody3DPtrData,
+): void {
+ out.bodyType = u8[ptr];
+ out.gravityScale = f32[(ptr + 4) >> 2];
+ out.linearDamping = f32[(ptr + 8) >> 2];
+ out.angularDamping = f32[(ptr + 12) >> 2];
+ out.fixedRotation = u8[ptr + 16] !== 0;
+ out.enabled = u8[ptr + 17] !== 0;
+}
+
+export function writeRigidBody3D(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: RigidBody3DPtrData,
+): void {
+ u8[ptr] = data.bodyType;
+ f32[(ptr + 4) >> 2] = data.gravityScale;
+ f32[(ptr + 8) >> 2] = data.linearDamping;
+ f32[(ptr + 12) >> 2] = data.angularDamping;
+ u8[ptr + 16] = data.fixedRotation ? 1 : 0;
+ u8[ptr + 17] = data.enabled ? 1 : 0;
+}
+
+export function createRigidBody3DData(): RigidBody3DPtrData {
+ return {
+ bodyType: 0,
+ gravityScale: 0,
+ linearDamping: 0,
+ angularDamping: 0,
+ fixedRotation: false,
+ enabled: false,
+ };
+}
+
export interface SegmentColliderPtrData {
point1: Vec2;
point2: Vec2;
@@ -1101,6 +1229,46 @@ export function createShapeRendererData(): ShapeRendererPtrData {
};
}
+export interface SphereCollider3DPtrData {
+ radius: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+}
+
+export function fillSphereCollider3D(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: SphereCollider3DPtrData,
+): void {
+ out.radius = f32[ptr >> 2];
+ out.friction = f32[(ptr + 4) >> 2];
+ out.restitution = f32[(ptr + 8) >> 2];
+ out.isSensor = u8[ptr + 12] !== 0;
+ out.enabled = u8[ptr + 13] !== 0;
+}
+
+export function writeSphereCollider3D(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: SphereCollider3DPtrData,
+): void {
+ f32[ptr >> 2] = data.radius;
+ f32[(ptr + 4) >> 2] = data.friction;
+ f32[(ptr + 8) >> 2] = data.restitution;
+ u8[ptr + 12] = data.isSensor ? 1 : 0;
+ u8[ptr + 13] = data.enabled ? 1 : 0;
+}
+
+export function createSphereCollider3DData(): SphereCollider3DPtrData {
+ return {
+ radius: 0,
+ friction: 0,
+ restitution: 0,
+ isSensor: false,
+ enabled: false,
+ };
+}
+
export interface SpineAnimationPtrData {
timeScale: number;
loop: boolean;
@@ -1762,9 +1930,11 @@ export interface PtrAccessor<T> {
export const PTR_ACCESSORS: Record<string, PtrAccessor<any>> = {
BitmapText: { fill: fillBitmapText, write: writeBitmapText, create: createBitmapTextData },
BoxCollider: { fill: fillBoxCollider, write: writeBoxCollider, create: createBoxColliderData },
+ BoxCollider3D: { fill: fillBoxCollider3D, write: writeBoxCollider3D, create: createBoxCollider3DData },
Camera: { fill: fillCamera, write: writeCamera, create: createCameraData },
Canvas: { fill: fillCanvas, write: writeCanvas, create: createCanvasData },
CapsuleCollider: { fill: fillCapsuleCollider, write: writeCapsuleCollider, create: createCapsuleColliderData },
+ CapsuleCollider3D: { fill: fillCapsuleCollider3D, write: writeCapsuleCollider3D, create: createCapsuleCollider3DData },
CircleCollider: { fill: fillCircleCollider, write: writeCircleCollider, create: createCircleColliderData },
DragonBonesAnimation: { fill: fillDragonBonesAnimation, write: writeDragonBonesAnimation, create: createDragonBonesAnimationData },
FlexContainer: { fill: fillFlexContainer, write: writeFlexContainer, create: createFlexContainerData },
@@ -1774,9 +1944,11 @@ export const PTR_ACCESSORS: Record<string, PtrAccessor<any>> = {
ParticleEmitter: { fill: fillParticleEmitter, write: writeParticleEmitter, create: createParticleEmitterData },
ParticleForceField: { fill: fillParticleForceField, write: writeParticleForceField, create: createParticleForceFieldData },
RigidBody: { fill: fillRigidBody, write: writeRigidBody, create: createRigidBodyData },
+ RigidBody3D: { fill: fillRigidBody3D, write: writeRigidBody3D, create: createRigidBody3DData },
SegmentCollider: { fill: fillSegmentCollider, write: writeSegmentCollider, create: createSegmentColliderData },
ShadowCaster2D: { fill: fillShadowCaster2D, write: writeShadowCaster2D, create: createShadowCaster2DData },
ShapeRenderer: { fill: fillShapeRenderer, write: writeShapeRenderer, create: createShapeRendererData },
+ SphereCollider3D: { fill: fillSphereCollider3D, write: writeSphereCollider3D, create: createSphereCollider3DData },
SpineAnimation: { fill: fillSpineAnimation, write: writeSpineAnimation, create: createSpineAnimationData },
Sprite: { fill: fillSprite, write: writeSprite, create: createSpriteData },
TilemapLayer: { fill: fillTilemapLayer, write: writeTilemapLayer, create: createTilemapLayerData },
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 1e0dfd42c..0fee4b433 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -15,7 +15,7 @@ import type { Dimension, Padding } from '../wasm/wasm.generated';
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '65f6ac377586cd75';
+export const ABI_LAYOUT_HASH = 'fb8d63de6b3e9865';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -129,6 +129,23 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
colorFields: [],
animatableFields: [],
},
+ BoxCollider3D: {
+ defaults: {
+ halfExtents: { x: 0.5, y: 0.5, z: 0.5 },
+ friction: 0.3,
+ restitution: 0,
+ isSensor: false,
+ enabled: true,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ friction: { min: 0 },
+ restitution: { min: 0, max: 1 },
+ },
+ },
Camera: {
defaults: {
projectionType: 0,
@@ -205,6 +222,26 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
colorFields: [],
animatableFields: [],
},
+ CapsuleCollider3D: {
+ defaults: {
+ radius: 0.3,
+ halfHeight: 0.5,
+ friction: 0.3,
+ restitution: 0,
+ isSensor: false,
+ enabled: true,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ radius: { min: 0 },
+ halfHeight: { min: 0 },
+ friction: { min: 0 },
+ restitution: { min: 0, max: 1 },
+ },
+ },
Children: {
defaults: {
entities: [],
@@ -548,6 +585,26 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
bodyType: { enum: [{ label: 'Static', value: 0 }, { label: 'Kinematic', value: 1 }, { label: 'Dynamic', value: 2 }] },
},
},
+ RigidBody3D: {
+ defaults: {
+ bodyType: 2,
+ gravityScale: 1,
+ linearDamping: 0.05,
+ angularDamping: 0.05,
+ fixedRotation: false,
+ enabled: true,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ bodyType: { enum: [{ label: 'Static', value: 0 }, { label: 'Kinematic', value: 1 }, { label: 'Dynamic', value: 2 }] },
+ gravityScale: { min: 0 },
+ linearDamping: { min: 0 },
+ angularDamping: { min: 0 },
+ },
+ },
SegmentCollider: {
defaults: {
point1: { x: -0.5, y: 0 },
@@ -601,6 +658,24 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
parallax: { tooltip: "Parallax scroll factor (1 = with world, <1 = slower, 0 = locked to camera).", advanced: true },
},
},
+ SphereCollider3D: {
+ defaults: {
+ radius: 0.5,
+ friction: 0.3,
+ restitution: 0,
+ isSensor: false,
+ enabled: true,
+ },
+ assetFields: [],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ radius: { min: 0 },
+ friction: { min: 0 },
+ restitution: { min: 0, max: 1 },
+ },
+ },
SpineAnimation: {
defaults: {
skeletonPath: '',
@@ -913,6 +988,14 @@ export interface BoxColliderData {
maskBits: number;
}
+export interface BoxCollider3DData {
+ halfExtents: Vec3;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+}
+
export interface CameraData {
projectionType: number;
fov: number;
@@ -950,6 +1033,15 @@ export interface CapsuleColliderData {
maskBits: number;
}
+export interface CapsuleCollider3DData {
+ radius: number;
+ halfHeight: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+}
+
/**
* The fields of the engine's `Children` component, generated from
* the C++ struct so the two shapes cannot drift.
@@ -1130,6 +1222,15 @@ export interface RigidBodyData {
enabled: boolean;
}
+export interface RigidBody3DData {
+ bodyType: number;
+ gravityScale: number;
+ linearDamping: number;
+ angularDamping: number;
+ fixedRotation: boolean;
+ enabled: boolean;
+}
+
export interface SegmentColliderData {
point1: Vec2;
point2: Vec2;
@@ -1157,6 +1258,14 @@ export interface ShapeRendererData {
enabled: boolean;
}
+export interface SphereCollider3DData {
+ radius: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+}
+
export interface SpineAnimationData {
skeletonPath: string;
atlasPath: string;
diff --git a/sdk/src/physics3d/Physics3DComponents.ts b/sdk/src/physics3d/Physics3DComponents.ts
new file mode 100644
index 000000000..a1ef5dc1b
--- /dev/null
+++ b/sdk/src/physics3d/Physics3DComponents.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Physics3DComponents.ts
+ * @brief The 3D world's components, as a scene authors them.
+ * @details Their own set rather than a third dimension on the 2D ones: a 2D scene
+ * keeps the solver, units and feel it already has, and pays nothing for a
+ * world it never asks for.
+ */
+import { defineBuiltin } from '../ecs/component';
+import type {
+ RigidBody3DData, BoxCollider3DData, SphereCollider3DData, CapsuleCollider3DData,
+} from '../ecs/component.generated';
+
+export type {
+ RigidBody3DData, BoxCollider3DData, SphereCollider3DData, CapsuleCollider3DData,
+};
+
+export const RigidBody3D = defineBuiltin<RigidBody3DData>('RigidBody3D', {
+ bodyType: 2,
+ gravityScale: 1.0,
+ linearDamping: 0.05,
+ angularDamping: 0.05,
+ fixedRotation: false,
+ enabled: true,
+}, {
+ fields: {
+ linearDamping: { min: 0, advanced: true },
+ angularDamping: { min: 0, advanced: true },
+ fixedRotation: { advanced: true },
+ },
+});
+
+export const BoxCollider3D = defineBuiltin<BoxCollider3DData>('BoxCollider3D', {
+ halfExtents: { x: 0.5, y: 0.5, z: 0.5 },
+ friction: 0.3,
+ restitution: 0.0,
+ isSensor: false,
+ enabled: true,
+});
+
+export const SphereCollider3D = defineBuiltin<SphereCollider3DData>('SphereCollider3D', {
+ radius: 0.5,
+ friction: 0.3,
+ restitution: 0.0,
+ isSensor: false,
+ enabled: true,
+});
+
+export const CapsuleCollider3D = defineBuiltin<CapsuleCollider3DData>('CapsuleCollider3D', {
+ radius: 0.3,
+ halfHeight: 0.5,
+ friction: 0.3,
+ restitution: 0.0,
+ isSensor: false,
+ enabled: true,
+});
diff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.ts
new file mode 100644
index 000000000..fbb588ea5
--- /dev/null
+++ b/sdk/src/physics3d/Physics3DModule.ts
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Physics3DModule.ts
+ * @brief The 3D physics wasm module's surface, and how it is loaded.
+ */
+
+/** What the module exports. Kept in step with Physics3DModuleEntry.cpp by
+ * {@link assertPhysics3DContract} — a TypeScript interface is gone at run time,
+ * and a module built before the JS that drives it installs happily and then
+ * throws once per frame for the length of the session. */
+export interface Physics3DWasmModule {
+ _physics3d_init(gx: number, gy: number, gz: number, maxBodies: number): void;
+ _physics3d_shutdown(): void;
+ _physics3d_isReady(): number;
+ _physics3d_step(dt: number, collisionSteps: number): void;
+ _physics3d_optimize(): void;
+
+ _physics3d_addBox(entity: number, hx: number, hy: number, hz: number,
+ px: number, py: number, pz: number,
+ qx: number, qy: number, qz: number, qw: number,
+ motion: number, gravityScale: number, linearDamping: number,
+ angularDamping: number, fixedRotation: number,
+ friction: number, restitution: number, isSensor: number): number;
+ _physics3d_addSphere(entity: number, radius: number,
+ px: number, py: number, pz: number,
+ qx: number, qy: number, qz: number, qw: number,
+ motion: number, gravityScale: number, linearDamping: number,
+ angularDamping: number, fixedRotation: number,
+ friction: number, restitution: number, isSensor: number): number;
+ _physics3d_addCapsule(entity: number, radius: number, halfHeight: number,
+ px: number, py: number, pz: number,
+ qx: number, qy: number, qz: number, qw: number,
+ motion: number, gravityScale: number, linearDamping: number,
+ angularDamping: number, fixedRotation: number,
+ friction: number, restitution: number, isSensor: number): number;
+ _physics3d_removeBody(bodyId: number): void;
+ _physics3d_setTransform(bodyId: number, px: number, py: number, pz: number,
+ qx: number, qy: number, qz: number, qw: number): void;
+ _physics3d_setLinearVelocity(bodyId: number, vx: number, vy: number, vz: number): void;
+ _physics3d_getBodyState(bodyId: number): number;
+
+ _physics3d_raycast(ox: number, oy: number, oz: number,
+ dx: number, dy: number, dz: number): number;
+
+ _physics3d_transforms(): number;
+ _physics3d_transformsBytes(): number;
+ _physics3d_queryResult(): number;
+ _physics3d_queryResultBytes(): number;
+
+ HEAPF32: Float32Array;
+ HEAPU32: Uint32Array;
+}
+
+export type Physics3DModuleFactory =
+ (options?: { wasmBinary?: ArrayBuffer }) => Promise<Physics3DWasmModule>;
+
+/** One readback record: entity, position, rotation. */
+export const PHYSICS3D_TRANSFORM_STRIDE = 8;
+
+const REQUIRED_EXPORTS = [
+ '_physics3d_init', '_physics3d_shutdown', '_physics3d_isReady', '_physics3d_step',
+ '_physics3d_addBox', '_physics3d_addSphere', '_physics3d_addCapsule',
+ '_physics3d_removeBody', '_physics3d_setTransform', '_physics3d_raycast',
+ '_physics3d_transforms', '_physics3d_transformsBytes',
+] as const;
+
+/** Throws naming what is missing, rather than letting the first frame do it. */
+export function assertPhysics3DContract(module: unknown): void {
+ const bag = module as Record<string, unknown>;
+ const missing = REQUIRED_EXPORTS.filter((name) => typeof bag?.[name] !== 'function');
+ if (missing.length > 0) {
+ throw new Error(`physics3d.wasm is missing ${missing.join(', ')} — it was built `
+ + 'from sources older than the code driving it');
+ }
+}
+
+/** Load the module from `url`, or adopt a factory a host already resolved. */
+export async function loadPhysics3DModule(
+ url: string, factory?: Physics3DModuleFactory,
+): Promise<Physics3DWasmModule> {
+ const resolved = factory
+ ?? ((await import(/* @vite-ignore */ url)) as { default: Physics3DModuleFactory }).default;
+ const module = await resolved();
+ assertPhysics3DContract(module);
+ return module;
+}
diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.ts
new file mode 100644
index 000000000..54e99d158
--- /dev/null
+++ b/sdk/src/physics3d/Physics3DPlugin.ts
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Physics3DPlugin.ts
+ * @brief Loads the 3D physics module and drives one world from the ECS.
+ */
+import type { App, Plugin } from '../app/app';
+import { Schedule, defineSystem } from '../ecs/system';
+import { defineResource } from '../ecs/resource';
+import type { Entity } from '../types';
+import {
+ loadPhysics3DModule, type Physics3DModuleFactory, type Physics3DWasmModule,
+} from './Physics3DModule';
+import {
+ stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG, type Physics3DConfig,
+} from './Physics3DSystem';
+
+/** The live module and the promise that resolves it, for a caller that must wait. */
+export interface Physics3DRuntime {
+ module: Physics3DWasmModule | null;
+ initPromise: Promise<unknown> | null;
+ /** Entity -> body id, so a scene teardown can drop the world's population. */
+ bodies: Map<Entity, number>;
+}
+
+export const Physics3DRuntime = defineResource<Physics3DRuntime>(
+ { module: null, initPromise: null, bodies: new Map() },
+ 'Physics3DRuntime',
+);
+
+export class Physics3DPlugin implements Plugin {
+ name = 'physics3d';
+ private config_: Physics3DConfig;
+ private wasmUrl_: string;
+ private factory_?: Physics3DModuleFactory;
+ private module_: Physics3DWasmModule | null = null;
+
+ constructor(wasmUrl: string, config: Partial<Physics3DConfig> = {},
+ factory?: Physics3DModuleFactory) {
+ this.wasmUrl_ = wasmUrl;
+ this.factory_ = factory;
+ this.config_ = { ...DEFAULT_PHYSICS3D_CONFIG, ...config };
+ }
+
+ build(app: App): void {
+ const runtime: Physics3DRuntime = { module: null, initPromise: null, bodies: new Map() };
+ app.insertResource(Physics3DRuntime, runtime);
+ app.subsystems?.transition?.('physics3d', 'initializing');
+
+ const initPromise = loadPhysics3DModule(this.wasmUrl_, this.factory_).then((module) => {
+ this.module_ = module;
+ const { gravity, maxBodies } = this.config_;
+ module._physics3d_init(gravity.x, gravity.y, gravity.z, maxBodies);
+ runtime.module = module;
+ app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([], () => {
+ stepPhysics3D(app, module, runtime.bodies, this.config_);
+ }));
+ app.setFixedTimestep?.(this.config_.fixedTimestep);
+ app.subsystems?.transition?.('physics3d', 'ready');
+ });
+
+ initPromise.catch((e: unknown) => {
+ app.subsystems?.markError?.('physics3d',
+ e instanceof Error ? e.message : String(e));
+ });
+ runtime.initPromise = initPromise;
+ }
+
+ /** Tear the world down, so a re-init does not inherit the last one's bodies. */
+ cleanup(): void {
+ this.module_?._physics3d_shutdown();
+ this.module_ = null;
+ }
+}
+
+export function physics3dPlugin(
+ wasmUrl: string, config: Partial<Physics3DConfig> = {}, factory?: Physics3DModuleFactory,
+): Physics3DPlugin {
+ return new Physics3DPlugin(wasmUrl, config, factory);
+}
diff --git a/sdk/src/physics3d/Physics3DSystem.ts b/sdk/src/physics3d/Physics3DSystem.ts
new file mode 100644
index 000000000..260a50f66
--- /dev/null
+++ b/sdk/src/physics3d/Physics3DSystem.ts
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Physics3DSystem.ts
+ * @brief Keeps the 3D world and the ECS saying the same thing.
+ * @details Each fixed step: entities that gained a RigidBody3D get a body, ones
+ * that lost it give theirs back, the world advances, and what moved is
+ * written to its Transform.
+ *
+ * Positions cross in METRES and land in world units, the same
+ * pixels-per-unit contract the 2D world uses: a solver tuned for metres
+ * behaves nothing like itself when a character is 180 units tall.
+ */
+import type { App } from '../app/app';
+import { Transform } from '../ecs/component';
+import type { TransformData } from '../ecs/component.generated';
+import {
+ RigidBody3D, BoxCollider3D, SphereCollider3D, CapsuleCollider3D,
+ type RigidBody3DData, type BoxCollider3DData, type SphereCollider3DData,
+ type CapsuleCollider3DData,
+} from './Physics3DComponents';
+import type { Entity } from '../types';
+import type { Physics3DWasmModule } from './Physics3DModule';
+import { PHYSICS3D_TRANSFORM_STRIDE } from './Physics3DModule';
+
+/** Body kinds, in the order the module reads them. */
+const MOTION = { Static: 0, Kinematic: 1, Dynamic: 2 } as const;
+
+export interface Physics3DConfig {
+ gravity: { x: number; y: number; z: number };
+ fixedTimestep: number;
+ collisionSteps: number;
+ pixelsPerUnit: number;
+ maxBodies: number;
+}
+
+export const DEFAULT_PHYSICS3D_CONFIG: Physics3DConfig = {
+ gravity: { x: 0, y: -9.81, z: 0 },
+ fixedTimestep: 1 / 60,
+ collisionSteps: 1,
+ pixelsPerUnit: 100,
+ maxBodies: 1024,
+};
+
+/** Which body an entity owns, so a removed component takes its body with it. */
+type BodyMap = Map<Entity, number>;
+
+function motionOf(body: RigidBody3DData): number {
+ // BodyType is the 2D enum, reused: static/kinematic/dynamic mean the same here.
+ return body.bodyType === 0 ? MOTION.Static
+ : body.bodyType === 1 ? MOTION.Kinematic : MOTION.Dynamic;
+}
+
+/**
+ * Create the body an entity's collider describes.
+ * @returns the module's body id, or 0 when the entity carries no 3D collider.
+ */
+function createBody(app: App, module: Physics3DWasmModule, entity: Entity,
+ body: RigidBody3DData, ppu: number): number {
+ const t = app.world.get(entity, Transform) as TransformData | undefined;
+ const p = t?.worldPosition ?? { x: 0, y: 0, z: 0 };
+ const r = t?.worldRotation ?? { x: 0, y: 0, z: 0, w: 1 };
+ const px = p.x / ppu, py = p.y / ppu, pz = p.z / ppu;
+ // How the body answers to the world, in the order the module reads it.
+ const how = [motionOf(body), body.gravityScale, body.linearDamping,
+ body.angularDamping, body.fixedRotation ? 1 : 0] as const;
+
+ const box = app.world.get(entity, BoxCollider3D) as BoxCollider3DData | undefined;
+ if (box?.enabled) {
+ return module._physics3d_addBox(
+ entity as number, box.halfExtents.x / ppu, box.halfExtents.y / ppu,
+ box.halfExtents.z / ppu, px, py, pz, r.x, r.y, r.z, r.w,
+ ...how, box.friction, box.restitution, box.isSensor ? 1 : 0);
+ }
+ const sphere = app.world.get(entity, SphereCollider3D) as SphereCollider3DData | undefined;
+ if (sphere?.enabled) {
+ return module._physics3d_addSphere(
+ entity as number, sphere.radius / ppu, px, py, pz, r.x, r.y, r.z, r.w,
+ ...how, sphere.friction, sphere.restitution, sphere.isSensor ? 1 : 0);
+ }
+ const capsule = app.world.get(entity, CapsuleCollider3D) as CapsuleCollider3DData | undefined;
+ if (capsule?.enabled) {
+ return module._physics3d_addCapsule(
+ entity as number, capsule.radius / ppu, capsule.halfHeight / ppu,
+ px, py, pz, r.x, r.y, r.z, r.w,
+ ...how, capsule.friction, capsule.restitution, capsule.isSensor ? 1 : 0);
+ }
+ // A body with no shape has no extent to collide with, so it is not registered
+ // at all — the alternative is an invisible point that falls forever.
+ return 0;
+}
+
+/** Bring the world's population in line with the ECS, then step and read back. */
+export function stepPhysics3D(app: App, module: Physics3DWasmModule,
+ bodies: BodyMap, config: Physics3DConfig): void {
+ const ppu = config.pixelsPerUnit;
+
+ const live = new Set<Entity>();
+ for (const entity of app.world.queryEntities([RigidBody3D])) {
+ const body = app.world.get(entity, RigidBody3D) as RigidBody3DData;
+ if (!body.enabled) continue;
+ live.add(entity);
+ if (!bodies.has(entity)) {
+ const id = createBody(app, module, entity, body, ppu);
+ if (id !== 0) bodies.set(entity, id);
+ }
+ }
+ for (const [entity, id] of bodies) {
+ if (live.has(entity) && app.world.valid(entity)) continue;
+ module._physics3d_removeBody(id);
+ bodies.delete(entity);
+ }
+
+ module._physics3d_step(config.fixedTimestep, config.collisionSteps);
+
+ // Only bodies the solver moved are in the buffer, so this is the frame's
+ // moving population rather than every body in the world.
+ const bytes = module._physics3d_transformsBytes();
+ if (bytes === 0) return;
+ const base = module._physics3d_transforms() >> 2;
+ const f32 = module.HEAPF32;
+ const count = bytes / 4 / PHYSICS3D_TRANSFORM_STRIDE;
+ for (let i = 0; i < count; i++) {
+ const o = base + i * PHYSICS3D_TRANSFORM_STRIDE;
+ const entity = f32[o] as Entity;
+ if (!app.world.valid(entity) || !app.world.has(entity, Transform)) continue;
+ const t = app.world.get(entity, Transform) as TransformData;
+ // Position and rotation are the solver's; scale is the scene's and is
+ // left alone, the same division of ownership the 2D path makes.
+ t.position.x = f32[o + 1]! * ppu;
+ t.position.y = f32[o + 2]! * ppu;
+ t.position.z = f32[o + 3]! * ppu;
+ t.rotation.x = f32[o + 4]!;
+ t.rotation.y = f32[o + 5]!;
+ t.rotation.z = f32[o + 6]!;
+ t.rotation.w = f32[o + 7]!;
+ app.world.set(entity, Transform, t);
+ }
+}
diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.ts
index dc9ffd00d..bacc332f5 100644
--- a/sdk/src/wasm/ptrLayouts.generated.ts
+++ b/sdk/src/wasm/ptrLayouts.generated.ts
@@ -54,6 +54,16 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'maskBits', type: 'u32', offset: 36 },
],
},
+ BoxCollider3D: {
+ ptrFn: 'getBoxCollider3DPtr',
+ fields: [
+ { name: 'halfExtents', type: 'vec3', offset: 0 },
+ { name: 'friction', type: 'f32', offset: 12 },
+ { name: 'restitution', type: 'f32', offset: 16 },
+ { name: 'isSensor', type: 'bool', offset: 20 },
+ { name: 'enabled', type: 'bool', offset: 21 },
+ ],
+ },
Camera: {
ptrFn: 'getCameraPtr',
fields: [
@@ -97,6 +107,17 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'maskBits', type: 'u32', offset: 36 },
],
},
+ CapsuleCollider3D: {
+ ptrFn: 'getCapsuleCollider3DPtr',
+ fields: [
+ { name: 'radius', type: 'f32', offset: 0 },
+ { name: 'halfHeight', type: 'f32', offset: 4 },
+ { name: 'friction', type: 'f32', offset: 8 },
+ { name: 'restitution', type: 'f32', offset: 12 },
+ { name: 'isSensor', type: 'bool', offset: 16 },
+ { name: 'enabled', type: 'bool', offset: 17 },
+ ],
+ },
CircleCollider: {
ptrFn: 'getCircleColliderPtr',
fields: [
@@ -267,6 +288,17 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'enabled', type: 'bool', offset: 18 },
],
},
+ RigidBody3D: {
+ ptrFn: 'getRigidBody3DPtr',
+ fields: [
+ { name: 'bodyType', type: 'u8', offset: 0 },
+ { name: 'gravityScale', type: 'f32', offset: 4 },
+ { name: 'linearDamping', type: 'f32', offset: 8 },
+ { name: 'angularDamping', type: 'f32', offset: 12 },
+ { name: 'fixedRotation', type: 'bool', offset: 16 },
+ { name: 'enabled', type: 'bool', offset: 17 },
+ ],
+ },
SegmentCollider: {
ptrFn: 'getSegmentColliderPtr',
fields: [
@@ -300,6 +332,16 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'enabled', type: 'bool', offset: 44 },
],
},
+ SphereCollider3D: {
+ ptrFn: 'getSphereCollider3DPtr',
+ fields: [
+ { name: 'radius', type: 'f32', offset: 0 },
+ { name: 'friction', type: 'f32', offset: 4 },
+ { name: 'restitution', type: 'f32', offset: 8 },
+ { name: 'isSensor', type: 'bool', offset: 12 },
+ { name: 'enabled', type: 'bool', offset: 13 },
+ ],
+ },
SpineAnimation: {
ptrFn: 'getSpineAnimationPtr',
fields: [
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index 815cdb332..9ec1e4d58 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -242,6 +242,14 @@ export interface BoxCollider {
maskBits: number;
}
+export interface BoxCollider3D {
+ halfExtents: Vec3;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+}
+
export interface Camera {
projectionType: number;
fov: number;
@@ -279,6 +287,15 @@ export interface CapsuleCollider {
maskBits: number;
}
+export interface CapsuleCollider3D {
+ radius: number;
+ halfHeight: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+}
+
export interface Children {
entities: VectorEntity;
}
@@ -447,6 +464,15 @@ export interface RigidBody {
enabled: boolean;
}
+export interface RigidBody3D {
+ bodyType: number;
+ gravityScale: number;
+ linearDamping: number;
+ angularDamping: number;
+ fixedRotation: boolean;
+ enabled: boolean;
+}
+
export interface SegmentCollider {
point1: Vec2;
point2: Vec2;
@@ -474,6 +500,14 @@ export interface ShapeRenderer {
enabled: boolean;
}
+export interface SphereCollider3D {
+ radius: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+}
+
export interface SpineAnimation {
skeletonPath: string;
atlasPath: string;
@@ -634,6 +668,10 @@ export interface Registry {
getBoxCollider(entity: Entity): BoxCollider;
addBoxCollider(entity: Entity, component: BoxCollider): void;
removeBoxCollider(entity: Entity): void;
+ hasBoxCollider3D(entity: Entity): boolean;
+ getBoxCollider3D(entity: Entity): BoxCollider3D;
+ addBoxCollider3D(entity: Entity, component: BoxCollider3D): void;
+ removeBoxCollider3D(entity: Entity): void;
hasCamera(entity: Entity): boolean;
getCamera(entity: Entity): Camera;
addCamera(entity: Entity, component: Camera): void;
@@ -646,6 +684,10 @@ export interface Registry {
getCapsuleCollider(entity: Entity): CapsuleCollider;
addCapsuleCollider(entity: Entity, component: CapsuleCollider): void;
removeCapsuleCollider(entity: Entity): void;
+ hasCapsuleCollider3D(entity: Entity): boolean;
+ getCapsuleCollider3D(entity: Entity): CapsuleCollider3D;
+ addCapsuleCollider3D(entity: Entity, component: CapsuleCollider3D): void;
+ removeCapsuleCollider3D(entity: Entity): void;
hasChildren(entity: Entity): boolean;
getChildren(entity: Entity): Children;
addChildren(entity: Entity, component: Children): void;
@@ -694,6 +736,10 @@ export interface Registry {
getRigidBody(entity: Entity): RigidBody;
addRigidBody(entity: Entity, component: RigidBody): void;
removeRigidBody(entity: Entity): void;
+ hasRigidBody3D(entity: Entity): boolean;
+ getRigidBody3D(entity: Entity): RigidBody3D;
+ addRigidBody3D(entity: Entity, component: RigidBody3D): void;
+ removeRigidBody3D(entity: Entity): void;
hasSegmentCollider(entity: Entity): boolean;
getSegmentCollider(entity: Entity): SegmentCollider;
addSegmentCollider(entity: Entity, component: SegmentCollider): void;
@@ -706,6 +752,10 @@ export interface Registry {
getShapeRenderer(entity: Entity): ShapeRenderer;
addShapeRenderer(entity: Entity, component: ShapeRenderer): void;
removeShapeRenderer(entity: Entity): void;
+ hasSphereCollider3D(entity: Entity): boolean;
+ getSphereCollider3D(entity: Entity): SphereCollider3D;
+ addSphereCollider3D(entity: Entity, component: SphereCollider3D): void;
+ removeSphereCollider3D(entity: Entity): void;
hasSpineAnimation(entity: Entity): boolean;
getSpineAnimation(entity: Entity): SpineAnimation;
addSpineAnimation(entity: Entity, component: SpineAnimation): void;
@@ -766,9 +816,11 @@ export interface ESEngineModule {
getBuiltinComponentNames(): string[];
BitmapText: new () => BitmapText;
BoxCollider: new () => BoxCollider;
+ BoxCollider3D: new () => BoxCollider3D;
Camera: new () => Camera;
Canvas: new () => Canvas;
CapsuleCollider: new () => CapsuleCollider;
+ CapsuleCollider3D: new () => CapsuleCollider3D;
Children: new () => Children;
CircleCollider: new () => CircleCollider;
DragonBonesAnimation: new () => DragonBonesAnimation;
@@ -781,9 +833,11 @@ export interface ESEngineModule {
ParticleEmitter: new () => ParticleEmitter;
ParticleForceField: new () => ParticleForceField;
RigidBody: new () => RigidBody;
+ RigidBody3D: new () => RigidBody3D;
SegmentCollider: new () => SegmentCollider;
ShadowCaster2D: new () => ShadowCaster2D;
ShapeRenderer: new () => ShapeRenderer;
+ SphereCollider3D: new () => SphereCollider3D;
SpineAnimation: new () => SpineAnimation;
Sprite: new () => Sprite;
TilemapLayer: new () => TilemapLayer;
diff --git a/sdk/tests/physics3d-ecs.test.ts b/sdk/tests/physics3d-ecs.test.ts
new file mode 100644
index 000000000..ffe7fd256
--- /dev/null
+++ b/sdk/tests/physics3d-ecs.test.ts
@@ -0,0 +1,203 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The 3D world drives Transform, in the units a scene is authored in.
+ *
+ * check-physics3d proves the solver; this proves the wiring around it, which is
+ * where the units live. A scene is authored in world units and the solver works
+ * in metres, so a body that arrives unscaled is a character 180 metres tall
+ * falling through a floor 0.1m thick — every number still "works", and nothing
+ * behaves.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { Transform } from '../src/ecs/component';
+import type { TransformData } from '../src/ecs/component.generated';
+import {
+ RigidBody3D, BoxCollider3D, SphereCollider3D, CapsuleCollider3D,
+} from '../src/physics3d/Physics3DComponents';
+import { stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG } from '../src/physics3d/Physics3DSystem';
+import type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';
+import type { App } from '../src/app/app';
+import type { Entity } from '../src/types';
+
+/** A module that records what it was told, and can be made to answer a readback. */
+function fakeModule(): Physics3DWasmModule & {
+ calls: { name: string; args: number[] }[];
+ publish(records: number[]): void;
+} {
+ const calls: { name: string; args: number[] }[] = [];
+ const heap = new Float32Array(1024);
+ const record = (name: string) => (...args: number[]): number => {
+ calls.push({ name, args });
+ return calls.length; // a non-zero body id
+ };
+ let published = 0;
+ return {
+ calls,
+ publish(records: number[]) {
+ heap.set(records, 0);
+ published = records.length * 4;
+ },
+ HEAPF32: heap,
+ HEAPU32: new Uint32Array(heap.buffer),
+ _physics3d_init: record('init'),
+ _physics3d_shutdown: record('shutdown'),
+ _physics3d_isReady: () => 1,
+ _physics3d_step: record('step'),
+ _physics3d_optimize: record('optimize'),
+ _physics3d_addBox: record('addBox'),
+ _physics3d_addSphere: record('addSphere'),
+ _physics3d_addCapsule: record('addCapsule'),
+ _physics3d_removeBody: record('removeBody'),
+ _physics3d_setTransform: record('setTransform'),
+ _physics3d_setLinearVelocity: record('setLinearVelocity'),
+ _physics3d_getBodyState: record('getBodyState'),
+ _physics3d_raycast: record('raycast'),
+ _physics3d_transforms: () => 0,
+ _physics3d_transformsBytes: () => published,
+ _physics3d_queryResult: () => 0,
+ _physics3d_queryResultBytes: () => 0,
+ } as unknown as Physics3DWasmModule & {
+ calls: { name: string; args: number[] }[];
+ publish(records: number[]): void;
+ };
+}
+
+/** The slice of a World that stepPhysics3D touches. Real components, plain
+ * storage: what is under test is the sync, and a World needs a C++ registry. */
+function fakeWorld() {
+ const store = new Map<Entity, Map<unknown, Record<string, unknown>>>();
+ let next = 1;
+ return {
+ spawn(): Entity {
+ const e = next++ as Entity;
+ store.set(e, new Map());
+ return e;
+ },
+ insert<T>(e: Entity, def: unknown, data?: Partial<T>): T {
+ const defaults = (def as { _default?: object })._default ?? {};
+ const value = structuredClone({ ...defaults, ...(data ?? {}) });
+ store.get(e)!.set(def, value as Record<string, unknown>);
+ return value as T;
+ },
+ remove(e: Entity, def: unknown): void { store.get(e)?.delete(def); },
+ get(e: Entity, def: unknown): unknown { return store.get(e)?.get(def); },
+ set(e: Entity, def: unknown, value: unknown): void {
+ store.get(e)?.set(def, value as Record<string, unknown>);
+ },
+ has(e: Entity, def: unknown): boolean { return store.get(e)?.has(def) ?? false; },
+ valid(e: Entity): boolean { return store.has(e); },
+ queryEntities(defs: unknown[]): Entity[] {
+ return [...store.entries()]
+ .filter(([, comps]) => defs.every((d) => comps.has(d)))
+ .map(([e]) => e);
+ },
+ };
+}
+
+describe('the 3D world and the ECS', () => {
+ let world: ReturnType<typeof fakeWorld>;
+ let app: App;
+ let module: ReturnType<typeof fakeModule>;
+ let bodies: Map<Entity, number>;
+
+ beforeEach(() => {
+ world = fakeWorld();
+ app = { world } as unknown as App;
+ module = fakeModule();
+ bodies = new Map();
+ });
+
+ const spawn = (position = { x: 0, y: 0, z: 0 }): Entity => {
+ const e = world.spawn();
+ world.insert<TransformData>(e, Transform, {
+ position: { ...position },
+ rotation: { x: 0, y: 0, z: 0, w: 1 },
+ scale: { x: 1, y: 1, z: 1 },
+ worldPosition: { ...position },
+ worldRotation: { x: 0, y: 0, z: 0, w: 1 },
+ worldScale: { x: 1, y: 1, z: 1 },
+ });
+ world.insert(e, RigidBody3D);
+ return e;
+ };
+
+ const called = (name: string) => module.calls.filter((c) => c.name === name);
+
+ it('registers a body for each shape a scene authors', () => {
+ const box = spawn();
+ world.insert(box, BoxCollider3D);
+ const ball = spawn();
+ world.insert(ball, SphereCollider3D);
+ const character = spawn();
+ world.insert(character, CapsuleCollider3D);
+
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
+
+ expect(called('addBox')).toHaveLength(1);
+ expect(called('addSphere')).toHaveLength(1);
+ expect(called('addCapsule')).toHaveLength(1);
+ expect(bodies.size).toBe(3);
+ });
+
+ it('registers nothing for a body with no shape', () => {
+ spawn();
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
+ // An extent-less body is a point that falls forever — and, worse, one the
+ // readback would then try to write back to a Transform.
+ expect(bodies.size).toBe(0);
+ expect(called('step')).toHaveLength(1);
+ });
+
+ it('sends the solver metres, not world units', () => {
+ const e = spawn({ x: 300, y: 150, z: 0 });
+ world.insert(e, SphereCollider3D);
+ (world.get(e, SphereCollider3D) as { radius: number }).radius = 50;
+
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
+
+ // 100 world units to the metre: a 50-unit ball is half a metre across and
+ // stands 1.5m from the origin.
+ const [call] = called('addSphere');
+ expect(call!.args[1]).toBeCloseTo(0.5, 6);
+ expect(call!.args[2]).toBeCloseTo(3, 6);
+ expect(call!.args[3]).toBeCloseTo(1.5, 6);
+ });
+
+ it('writes the solver’s answer back in world units', () => {
+ const e = spawn();
+ world.insert(e, BoxCollider3D);
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
+
+ // (entity, position, rotation) — a body at 2m up and a quarter turn about Y.
+ const s = Math.SQRT1_2;
+ module.publish([e as number, 0, 2, 0, 0, s, 0, s]);
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
+
+ const t = world.get(e, Transform) as TransformData;
+ expect(t.position.y).toBeCloseTo(200, 4);
+ expect(t.rotation.y).toBeCloseTo(s, 6);
+ expect(t.rotation.w).toBeCloseTo(s, 6);
+ });
+
+ it('gives a body back when its component goes', () => {
+ const e = spawn();
+ world.insert(e, BoxCollider3D);
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
+ expect(bodies.size).toBe(1);
+
+ world.remove(e, RigidBody3D);
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
+ expect(called('removeBody')).toHaveLength(1);
+ expect(bodies.size).toBe(0);
+ });
+
+ it('leaves a disabled body out of the world', () => {
+ const e = spawn();
+ world.insert(e, BoxCollider3D);
+ (world.get(e, RigidBody3D) as { enabled: boolean }).enabled = false;
+
+ stepPhysics3D(app, module, bodies, DEFAULT_PHYSICS3D_CONFIG);
+ expect(bodies.size).toBe(0);
+ });
+});
diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjs
index 6f2f3fd37..784d589ee 100644
--- a/sdk/tests/physics3d-smoke.mjs
+++ b/sdk/tests/physics3d-smoke.mjs
@@ -20,6 +20,9 @@ const near = (a, b, tol = 1e-3) => Math.abs(a - b) <= tol;
const STATIC = 0, KINEMATIC = 1, DYNAMIC = 2;
const IDENTITY = [0, 0, 0, 1];
+// motion, gravityScale, linearDamping, angularDamping, fixedRotation — what a body
+// is beyond its shape.
+const FREE = (motion) => [motion, 1, 0, 0, 0];
/** The position of `entity` in the step's transform readback, or null. */
function bodyPos(entity) {
@@ -59,8 +62,8 @@ check('the world reports itself ready', m._physics3d_isReady() === 1);
// Floor spans y in [-1, 0]; a sphere of radius 0.5 dropped from y=4 comes to rest
// with its CENTRE at 0.5 — the one number that says contact resolution ran.
const FLOOR = 1, BALL = 2;
-m._physics3d_addBox(FLOOR, 50, 0.5, 50, 0, -0.5, 0, ...IDENTITY, STATIC, 0.5, 0, 0);
-const ballId = m._physics3d_addSphere(BALL, 0.5, 0, 4, 0, ...IDENTITY, DYNAMIC, 0.5, 0, 0);
+m._physics3d_addBox(FLOOR, 50, 0.5, 50, 0, -0.5, 0, ...IDENTITY, ...FREE(STATIC), 0.5, 0, 0);
+const ballId = m._physics3d_addSphere(BALL, 0.5, 0, 4, 0, ...IDENTITY, ...FREE(DYNAMIC), 0.5, 0, 0);
m._physics3d_optimize();
check('a body id is handed back', ballId !== 0, `id=${ballId}`);
@@ -94,7 +97,7 @@ check('a ray into empty space misses', raycast(0, 10, 0, 0, 20, 0) === null);
// ── 3) Static bodies stay put, kinematic ones are moved by hand ─────────────
const PLATFORM = 3;
const platformId = m._physics3d_addBox(PLATFORM, 1, 0.25, 1, 5, 2, 0, ...IDENTITY,
- KINEMATIC, 0.5, 0, 0);
+ ...FREE(KINEMATIC), 0.5, 0, 0);
step(60);
const platform = bodyState(platformId);
check('a kinematic body ignores gravity', platform && near(platform.y, 2, 1e-3),
@@ -106,7 +109,7 @@ check('and goes where it is put', near(bodyState(platformId).y, 3, 1e-3));
// Radius 0.3 + half-height 0.5 puts the bottom cap 0.8 below the centre, so a
// resting capsule sits at 0.8.
const CAP = 4;
-const capId = m._physics3d_addCapsule(CAP, 0.3, 0.5, 3, 5, 0, ...IDENTITY, DYNAMIC, 0.5, 0, 0);
+const capId = m._physics3d_addCapsule(CAP, 0.3, 0.5, 3, 5, 0, ...IDENTITY, ...FREE(DYNAMIC), 0.5, 0, 0);
step(240);
const cap = bodyState(capId);
check('a capsule rests on its own half-height', cap && near(cap.y, 0.8, 0.05),
@@ -119,7 +122,29 @@ const side = raycast(10, 0.8, 0, -20, 0, 0);
check('and on its own radius', side && side.entity === CAP && near(side.fraction, 0.335, 0.01),
`entity=${side?.entity} fraction=${side?.fraction.toFixed(4)} want 0.335`);
-// ── 5) A removed body is gone from both the sweep and the getter ────────────
+// ── 5) What a body is beyond its shape ─────────────────────────────────────
+// gravityScale 0 is weightlessness, not slow falling: a body that never reads it
+// drops 4.9m in the same second.
+const FLOAT = 5;
+const floatId = m._physics3d_addSphere(FLOAT, 0.5, -3, 5, 0, ...IDENTITY,
+ DYNAMIC, 0, 0, 0, 0, 0.5, 0, 0);
+step(60);
+check('gravityScale 0 leaves a body where it was', near(bodyState(floatId).y, 5, 0.01),
+ `y=${bodyState(floatId).y.toFixed(4)} want 5`);
+
+// fixedRotation freezes the orientation a body was given — it does not right it.
+// This capsule starts tilted and lands on the floor; free to turn it would topple
+// flat, so the tilt it KEEPS is what says the solver may not turn it.
+const UPRIGHT = 6;
+const uprightId = m._physics3d_addCapsule(UPRIGHT, 0.3, 0.5, -6, 3, 0,
+ 0.3, 0, 0, 0.954, DYNAMIC, 1, 0, 0, 1, 0.5, 0, 0);
+step(180);
+const uprightBase = m._physics3d_getBodyState(uprightId) ? m._physics3d_queryResult() >> 2 : 0;
+const qx = m.HEAPF32[uprightBase + 3];
+check('fixedRotation keeps a body from turning', near(qx, 0.3, 0.01),
+ `qx=${qx?.toFixed(4)} want the 0.3 it was given`);
+
+// ── 6) A removed body is gone from both the sweep and the getter ────────────
m._physics3d_removeBody(capId);
step(1);
check('a removed body leaves the readback', bodyPos(CAP) === null);
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index 448c50b97..6435b86de 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash 535f4ea75f733a04
+ * @schema_hash 49337e5243bcd028
*/
-#define ES_EDITOR_API_SCHEMA_HASH "535f4ea75f733a04"
+#define ES_EDITOR_API_SCHEMA_HASH "49337e5243bcd028"
#include <emscripten/bind.h>
#include <string>
@@ -24,6 +24,7 @@
#include "../ecs/components/ParticleEmitter.hpp"
#include "../ecs/components/ParticleForceField.hpp"
#include "../ecs/components/RigidBody.hpp"
+#include "../ecs/components/RigidBody3D.hpp"
#include "../ecs/components/ShadowCaster2D.hpp"
#include "../ecs/components/ShapeRenderer.hpp"
#include "../ecs/components/SpineAnimation.hpp"
@@ -59,9 +60,11 @@ std::vector<std::string> editor_getComponentNames() {
return {
"BitmapText",
"BoxCollider",
+ "BoxCollider3D",
"Camera",
"Canvas",
"CapsuleCollider",
+ "CapsuleCollider3D",
"Children",
"CircleCollider",
"DragonBonesAnimation",
@@ -74,9 +77,11 @@ std::vector<std::string> editor_getComponentNames() {
"ParticleEmitter",
"ParticleForceField",
"RigidBody",
+ "RigidBody3D",
"SegmentCollider",
"ShadowCaster2D",
"ShapeRenderer",
+ "SphereCollider3D",
"SpineAnimation",
"Sprite",
"TilemapLayer",
@@ -124,6 +129,16 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"categoryBits","type":"int","group":"BoxCollider"},
{"key":"maskBits","type":"int","group":"BoxCollider"}
])JSON";
+ } else if (name == "BoxCollider3D") {
+ return R"JSON([
+ {"key":"halfExtents.x","type":"float","group":"BoxCollider3D"},
+ {"key":"halfExtents.y","type":"float","group":"BoxCollider3D"},
+ {"key":"halfExtents.z","type":"float","group":"BoxCollider3D"},
+ {"key":"friction","type":"float","group":"BoxCollider3D"},
+ {"key":"restitution","type":"float","group":"BoxCollider3D"},
+ {"key":"isSensor","type":"bool","group":"BoxCollider3D"},
+ {"key":"enabled","type":"bool","group":"BoxCollider3D"}
+ ])JSON";
} else if (name == "Camera") {
return R"JSON([
{"key":"projectionType","type":"enum","group":"Camera","values":["Perspective","Orthographic"]},
@@ -169,6 +184,15 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"categoryBits","type":"int","group":"CapsuleCollider"},
{"key":"maskBits","type":"int","group":"CapsuleCollider"}
])JSON";
+ } else if (name == "CapsuleCollider3D") {
+ return R"JSON([
+ {"key":"radius","type":"float","group":"CapsuleCollider3D"},
+ {"key":"halfHeight","type":"float","group":"CapsuleCollider3D"},
+ {"key":"friction","type":"float","group":"CapsuleCollider3D"},
+ {"key":"restitution","type":"float","group":"CapsuleCollider3D"},
+ {"key":"isSensor","type":"bool","group":"CapsuleCollider3D"},
+ {"key":"enabled","type":"bool","group":"CapsuleCollider3D"}
+ ])JSON";
} else if (name == "Children") {
return R"JSON([
{"key":"entities","type":"entity","group":"Children"}
@@ -362,6 +386,15 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"bullet","type":"bool","group":"RigidBody"},
{"key":"enabled","type":"bool","group":"RigidBody"}
])JSON";
+ } else if (name == "RigidBody3D") {
+ return R"JSON([
+ {"key":"bodyType","type":"enum","group":"RigidBody3D","values":["Static","Kinematic","Dynamic"]},
+ {"key":"gravityScale","type":"float","group":"RigidBody3D"},
+ {"key":"linearDamping","type":"float","group":"RigidBody3D"},
+ {"key":"angularDamping","type":"float","group":"RigidBody3D"},
+ {"key":"fixedRotation","type":"bool","group":"RigidBody3D"},
+ {"key":"enabled","type":"bool","group":"RigidBody3D"}
+ ])JSON";
} else if (name == "SegmentCollider") {
return R"JSON([
{"key":"point1.x","type":"float","group":"SegmentCollider"},
@@ -397,6 +430,14 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"parallax.y","type":"float","group":"ShapeRenderer"},
{"key":"enabled","type":"bool","group":"ShapeRenderer"}
])JSON";
+ } else if (name == "SphereCollider3D") {
+ return R"JSON([
+ {"key":"radius","type":"float","group":"SphereCollider3D"},
+ {"key":"friction","type":"float","group":"SphereCollider3D"},
+ {"key":"restitution","type":"float","group":"SphereCollider3D"},
+ {"key":"isSensor","type":"bool","group":"SphereCollider3D"},
+ {"key":"enabled","type":"bool","group":"SphereCollider3D"}
+ ])JSON";
} else if (name == "SpineAnimation") {
return R"JSON([
{"key":"skeletonPath","type":"asset","group":"SpineAnimation"},
@@ -613,6 +654,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "BoxCollider") {
if (!reg.has<esengine::ecs::BoxCollider>(entity)) reg.emplace<esengine::ecs::BoxCollider>(entity);
return true;
+ } else if (name == "BoxCollider3D") {
+ if (!reg.has<esengine::ecs::BoxCollider3D>(entity)) reg.emplace<esengine::ecs::BoxCollider3D>(entity);
+ return true;
} else if (name == "Camera") {
if (!reg.has<esengine::ecs::Camera>(entity)) reg.emplace<esengine::ecs::Camera>(entity);
return true;
@@ -622,6 +666,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "CapsuleCollider") {
if (!reg.has<esengine::ecs::CapsuleCollider>(entity)) reg.emplace<esengine::ecs::CapsuleCollider>(entity);
return true;
+ } else if (name == "CapsuleCollider3D") {
+ if (!reg.has<esengine::ecs::CapsuleCollider3D>(entity)) reg.emplace<esengine::ecs::CapsuleCollider3D>(entity);
+ return true;
} else if (name == "Children") {
return false;
} else if (name == "CircleCollider") {
@@ -656,6 +703,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "RigidBody") {
if (!reg.has<esengine::ecs::RigidBody>(entity)) reg.emplace<esengine::ecs::RigidBody>(entity);
return true;
+ } else if (name == "RigidBody3D") {
+ if (!reg.has<esengine::ecs::RigidBody3D>(entity)) reg.emplace<esengine::ecs::RigidBody3D>(entity);
+ return true;
} else if (name == "SegmentCollider") {
if (!reg.has<esengine::ecs::SegmentCollider>(entity)) reg.emplace<esengine::ecs::SegmentCollider>(entity);
return true;
@@ -665,6 +715,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "ShapeRenderer") {
if (!reg.has<esengine::ecs::ShapeRenderer>(entity)) reg.emplace<esengine::ecs::ShapeRenderer>(entity);
return true;
+ } else if (name == "SphereCollider3D") {
+ if (!reg.has<esengine::ecs::SphereCollider3D>(entity)) reg.emplace<esengine::ecs::SphereCollider3D>(entity);
+ return true;
} else if (name == "SpineAnimation") {
if (!reg.has<esengine::ecs::SpineAnimation>(entity)) reg.emplace<esengine::ecs::SpineAnimation>(entity);
return true;
@@ -709,12 +762,16 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::BitmapText>(entity)) { reg.remove<esengine::ecs::BitmapText>(entity); return true; }
} else if (name == "BoxCollider") {
if (reg.has<esengine::ecs::BoxCollider>(entity)) { reg.remove<esengine::ecs::BoxCollider>(entity); return true; }
+ } else if (name == "BoxCollider3D") {
+ if (reg.has<esengine::ecs::BoxCollider3D>(entity)) { reg.remove<esengine::ecs::BoxCollider3D>(entity); return true; }
} else if (name == "Camera") {
if (reg.has<esengine::ecs::Camera>(entity)) { reg.remove<esengine::ecs::Camera>(entity); return true; }
} else if (name == "Canvas") {
if (reg.has<esengine::ecs::Canvas>(entity)) { reg.remove<esengine::ecs::Canvas>(entity); return true; }
} else if (name == "CapsuleCollider") {
if (reg.has<esengine::ecs::CapsuleCollider>(entity)) { reg.remove<esengine::ecs::CapsuleCollider>(entity); return true; }
+ } else if (name == "CapsuleCollider3D") {
+ if (reg.has<esengine::ecs::CapsuleCollider3D>(entity)) { reg.remove<esengine::ecs::CapsuleCollider3D>(entity); return true; }
} else if (name == "Children") {
if (reg.has<esengine::ecs::Children>(entity)) {
const auto kids = reg.get<esengine::ecs::Children>(entity).entities;
@@ -743,12 +800,16 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::ParticleForceField>(entity)) { reg.remove<esengine::ecs::ParticleForceField>(entity); return true; }
} else if (name == "RigidBody") {
if (reg.has<esengine::ecs::RigidBody>(entity)) { reg.remove<esengine::ecs::RigidBody>(entity); return true; }
+ } else if (name == "RigidBody3D") {
+ if (reg.has<esengine::ecs::RigidBody3D>(entity)) { reg.remove<esengine::ecs::RigidBody3D>(entity); return true; }
} else if (name == "SegmentCollider") {
if (reg.has<esengine::ecs::SegmentCollider>(entity)) { reg.remove<esengine::ecs::SegmentCollider>(entity); return true; }
} else if (name == "ShadowCaster2D") {
if (reg.has<esengine::ecs::ShadowCaster2D>(entity)) { reg.remove<esengine::ecs::ShadowCaster2D>(entity); return true; }
} else if (name == "ShapeRenderer") {
if (reg.has<esengine::ecs::ShapeRenderer>(entity)) { reg.remove<esengine::ecs::ShapeRenderer>(entity); return true; }
+ } else if (name == "SphereCollider3D") {
+ if (reg.has<esengine::ecs::SphereCollider3D>(entity)) { reg.remove<esengine::ecs::SphereCollider3D>(entity); return true; }
} else if (name == "SpineAnimation") {
if (reg.has<esengine::ecs::SpineAnimation>(entity)) { reg.remove<esengine::ecs::SpineAnimation>(entity); return true; }
} else if (name == "Sprite") {
@@ -780,9 +841,11 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (!reg.valid(entity)) return false;
if (name == "BitmapText") return reg.has<esengine::ecs::BitmapText>(entity);
if (name == "BoxCollider") return reg.has<esengine::ecs::BoxCollider>(entity);
+ if (name == "BoxCollider3D") return reg.has<esengine::ecs::BoxCollider3D>(entity);
if (name == "Camera") return reg.has<esengine::ecs::Camera>(entity);
if (name == "Canvas") return reg.has<esengine::ecs::Canvas>(entity);
if (name == "CapsuleCollider") return reg.has<esengine::ecs::CapsuleCollider>(entity);
+ if (name == "CapsuleCollider3D") return reg.has<esengine::ecs::CapsuleCollider3D>(entity);
if (name == "Children") return reg.has<esengine::ecs::Children>(entity);
if (name == "CircleCollider") return reg.has<esengine::ecs::CircleCollider>(entity);
if (name == "DragonBonesAnimation") return reg.has<esengine::ecs::DragonBonesAnimation>(entity);
@@ -795,9 +858,11 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "ParticleEmitter") return reg.has<esengine::ecs::ParticleEmitter>(entity);
if (name == "ParticleForceField") return reg.has<esengine::ecs::ParticleForceField>(entity);
if (name == "RigidBody") return reg.has<esengine::ecs::RigidBody>(entity);
+ if (name == "RigidBody3D") return reg.has<esengine::ecs::RigidBody3D>(entity);
if (name == "SegmentCollider") return reg.has<esengine::ecs::SegmentCollider>(entity);
if (name == "ShadowCaster2D") return reg.has<esengine::ecs::ShadowCaster2D>(entity);
if (name == "ShapeRenderer") return reg.has<esengine::ecs::ShapeRenderer>(entity);
+ if (name == "SphereCollider3D") return reg.has<esengine::ecs::SphereCollider3D>(entity);
if (name == "SpineAnimation") return reg.has<esengine::ecs::SpineAnimation>(entity);
if (name == "Sprite") return reg.has<esengine::ecs::Sprite>(entity);
if (name == "TilemapLayer") return reg.has<esengine::ecs::TilemapLayer>(entity);
@@ -820,9 +885,11 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (!reg.valid(entity)) return result;
if (reg.has<esengine::ecs::BitmapText>(entity)) result.push_back("BitmapText");
if (reg.has<esengine::ecs::BoxCollider>(entity)) result.push_back("BoxCollider");
+ if (reg.has<esengine::ecs::BoxCollider3D>(entity)) result.push_back("BoxCollider3D");
if (reg.has<esengine::ecs::Camera>(entity)) result.push_back("Camera");
if (reg.has<esengine::ecs::Canvas>(entity)) result.push_back("Canvas");
if (reg.has<esengine::ecs::CapsuleCollider>(entity)) result.push_back("CapsuleCollider");
+ if (reg.has<esengine::ecs::CapsuleCollider3D>(entity)) result.push_back("CapsuleCollider3D");
if (reg.has<esengine::ecs::Children>(entity)) result.push_back("Children");
if (reg.has<esengine::ecs::CircleCollider>(entity)) result.push_back("CircleCollider");
if (reg.has<esengine::ecs::DragonBonesAnimation>(entity)) result.push_back("DragonBonesAnimation");
@@ -835,9 +902,11 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::ParticleEmitter>(entity)) result.push_back("ParticleEmitter");
if (reg.has<esengine::ecs::ParticleForceField>(entity)) result.push_back("ParticleForceField");
if (reg.has<esengine::ecs::RigidBody>(entity)) result.push_back("RigidBody");
+ if (reg.has<esengine::ecs::RigidBody3D>(entity)) result.push_back("RigidBody3D");
if (reg.has<esengine::ecs::SegmentCollider>(entity)) result.push_back("SegmentCollider");
if (reg.has<esengine::ecs::ShadowCaster2D>(entity)) result.push_back("ShadowCaster2D");
if (reg.has<esengine::ecs::ShapeRenderer>(entity)) result.push_back("ShapeRenderer");
+ if (reg.has<esengine::ecs::SphereCollider3D>(entity)) result.push_back("SphereCollider3D");
if (reg.has<esengine::ecs::SpineAnimation>(entity)) result.push_back("SpineAnimation");
if (reg.has<esengine::ecs::Sprite>(entity)) result.push_back("Sprite");
if (reg.has<esengine::ecs::TilemapLayer>(entity)) result.push_back("TilemapLayer");
@@ -882,6 +951,16 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "restitution") { c.restitution = value; }
else { return false; }
return true;
+ } else if (comp == "BoxCollider3D") {
+ if (!reg.has<esengine::ecs::BoxCollider3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::BoxCollider3D>(entity);
+ if (field == "halfExtents.x") { c.halfExtents.x = value; }
+ else if (field == "halfExtents.y") { c.halfExtents.y = value; }
+ else if (field == "halfExtents.z") { c.halfExtents.z = value; }
+ else if (field == "friction") { c.friction = value; }
+ else if (field == "restitution") { c.restitution = value; }
+ else { return false; }
+ return true;
} else if (comp == "Camera") {
if (!reg.has<esengine::ecs::Camera>(entity)) return false;
auto& c = reg.get<esengine::ecs::Camera>(entity);
@@ -919,6 +998,15 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "restitution") { c.restitution = value; }
else { return false; }
return true;
+ } else if (comp == "CapsuleCollider3D") {
+ if (!reg.has<esengine::ecs::CapsuleCollider3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::CapsuleCollider3D>(entity);
+ if (field == "radius") { c.radius = value; }
+ else if (field == "halfHeight") { c.halfHeight = value; }
+ else if (field == "friction") { c.friction = value; }
+ else if (field == "restitution") { c.restitution = value; }
+ else { return false; }
+ return true;
} else if (comp == "CircleCollider") {
if (!reg.has<esengine::ecs::CircleCollider>(entity)) return false;
auto& c = reg.get<esengine::ecs::CircleCollider>(entity);
@@ -1048,6 +1136,14 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "angularDamping") { c.angularDamping = value; }
else { return false; }
return true;
+ } else if (comp == "RigidBody3D") {
+ if (!reg.has<esengine::ecs::RigidBody3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::RigidBody3D>(entity);
+ if (field == "gravityScale") { c.gravityScale = value; }
+ else if (field == "linearDamping") { c.linearDamping = value; }
+ else if (field == "angularDamping") { c.angularDamping = value; }
+ else { return false; }
+ return true;
} else if (comp == "SegmentCollider") {
if (!reg.has<esengine::ecs::SegmentCollider>(entity)) return false;
auto& c = reg.get<esengine::ecs::SegmentCollider>(entity);
@@ -1081,6 +1177,14 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "parallax.y") { c.parallax.y = value; }
else { return false; }
return true;
+ } else if (comp == "SphereCollider3D") {
+ if (!reg.has<esengine::ecs::SphereCollider3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::SphereCollider3D>(entity);
+ if (field == "radius") { c.radius = value; }
+ else if (field == "friction") { c.friction = value; }
+ else if (field == "restitution") { c.restitution = value; }
+ else { return false; }
+ return true;
} else if (comp == "SpineAnimation") {
if (!reg.has<esengine::ecs::SpineAnimation>(entity)) return false;
auto& c = reg.get<esengine::ecs::SpineAnimation>(entity);
@@ -1287,6 +1391,14 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "density") { return c.density; }
else if (field == "friction") { return c.friction; }
else if (field == "restitution") { return c.restitution; }
+ } else if (comp == "BoxCollider3D") {
+ if (!reg.has<esengine::ecs::BoxCollider3D>(entity)) return 0.0f;
+ const auto& c = reg.get<esengine::ecs::BoxCollider3D>(entity);
+ if (field == "halfExtents.x") { return c.halfExtents.x; }
+ else if (field == "halfExtents.y") { return c.halfExtents.y; }
+ else if (field == "halfExtents.z") { return c.halfExtents.z; }
+ else if (field == "friction") { return c.friction; }
+ else if (field == "restitution") { return c.restitution; }
} else if (comp == "Camera") {
if (!reg.has<esengine::ecs::Camera>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::Camera>(entity);
@@ -1318,6 +1430,13 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "density") { return c.density; }
else if (field == "friction") { return c.friction; }
else if (field == "restitution") { return c.restitution; }
+ } else if (comp == "CapsuleCollider3D") {
+ if (!reg.has<esengine::ecs::CapsuleCollider3D>(entity)) return 0.0f;
+ const auto& c = reg.get<esengine::ecs::CapsuleCollider3D>(entity);
+ if (field == "radius") { return c.radius; }
+ else if (field == "halfHeight") { return c.halfHeight; }
+ else if (field == "friction") { return c.friction; }
+ else if (field == "restitution") { return c.restitution; }
} else if (comp == "CircleCollider") {
if (!reg.has<esengine::ecs::CircleCollider>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::CircleCollider>(entity);
@@ -1431,6 +1550,12 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
if (field == "gravityScale") { return c.gravityScale; }
else if (field == "linearDamping") { return c.linearDamping; }
else if (field == "angularDamping") { return c.angularDamping; }
+ } else if (comp == "RigidBody3D") {
+ if (!reg.has<esengine::ecs::RigidBody3D>(entity)) return 0.0f;
+ const auto& c = reg.get<esengine::ecs::RigidBody3D>(entity);
+ if (field == "gravityScale") { return c.gravityScale; }
+ else if (field == "linearDamping") { return c.linearDamping; }
+ else if (field == "angularDamping") { return c.angularDamping; }
} else if (comp == "SegmentCollider") {
if (!reg.has<esengine::ecs::SegmentCollider>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::SegmentCollider>(entity);
@@ -1458,6 +1583,12 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "cornerRadius") { return c.cornerRadius; }
else if (field == "parallax.x") { return c.parallax.x; }
else if (field == "parallax.y") { return c.parallax.y; }
+ } else if (comp == "SphereCollider3D") {
+ if (!reg.has<esengine::ecs::SphereCollider3D>(entity)) return 0.0f;
+ const auto& c = reg.get<esengine::ecs::SphereCollider3D>(entity);
+ if (field == "radius") { return c.radius; }
+ else if (field == "friction") { return c.friction; }
+ else if (field == "restitution") { return c.restitution; }
} else if (comp == "SpineAnimation") {
if (!reg.has<esengine::ecs::SpineAnimation>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::SpineAnimation>(entity);
@@ -1727,6 +1858,12 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
if (field == "bodyType") { c.bodyType = static_cast<BodyType>(value); }
else { return false; }
return true;
+ } else if (comp == "RigidBody3D") {
+ if (!reg.has<esengine::ecs::RigidBody3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::RigidBody3D>(entity);
+ if (field == "bodyType") { c.bodyType = static_cast<BodyType>(value); }
+ else { return false; }
+ return true;
} else if (comp == "SegmentCollider") {
if (!reg.has<esengine::ecs::SegmentCollider>(entity)) return false;
auto& c = reg.get<esengine::ecs::SegmentCollider>(entity);
@@ -1908,6 +2045,10 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
if (!reg.has<esengine::ecs::RigidBody>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::RigidBody>(entity);
if (field == "bodyType") { return static_cast<i32>(c.bodyType); }
+ } else if (comp == "RigidBody3D") {
+ if (!reg.has<esengine::ecs::RigidBody3D>(entity)) return 0;
+ const auto& c = reg.get<esengine::ecs::RigidBody3D>(entity);
+ if (field == "bodyType") { return static_cast<i32>(c.bodyType); }
} else if (comp == "SegmentCollider") {
if (!reg.has<esengine::ecs::SegmentCollider>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::SegmentCollider>(entity);
@@ -1992,6 +2133,13 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "enabled") { c.enabled = value; }
else { return false; }
return true;
+ } else if (comp == "BoxCollider3D") {
+ if (!reg.has<esengine::ecs::BoxCollider3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::BoxCollider3D>(entity);
+ if (field == "isSensor") { c.isSensor = value; }
+ else if (field == "enabled") { c.enabled = value; }
+ else { return false; }
+ return true;
} else if (comp == "Camera") {
if (!reg.has<esengine::ecs::Camera>(entity)) return false;
auto& c = reg.get<esengine::ecs::Camera>(entity);
@@ -2006,6 +2154,13 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "enabled") { c.enabled = value; }
else { return false; }
return true;
+ } else if (comp == "CapsuleCollider3D") {
+ if (!reg.has<esengine::ecs::CapsuleCollider3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::CapsuleCollider3D>(entity);
+ if (field == "isSensor") { c.isSensor = value; }
+ else if (field == "enabled") { c.enabled = value; }
+ else { return false; }
+ return true;
} else if (comp == "CircleCollider") {
if (!reg.has<esengine::ecs::CircleCollider>(entity)) return false;
auto& c = reg.get<esengine::ecs::CircleCollider>(entity);
@@ -2073,6 +2228,13 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
else if (field == "enabled") { c.enabled = value; }
else { return false; }
return true;
+ } else if (comp == "RigidBody3D") {
+ if (!reg.has<esengine::ecs::RigidBody3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::RigidBody3D>(entity);
+ if (field == "fixedRotation") { c.fixedRotation = value; }
+ else if (field == "enabled") { c.enabled = value; }
+ else { return false; }
+ return true;
} else if (comp == "SegmentCollider") {
if (!reg.has<esengine::ecs::SegmentCollider>(entity)) return false;
auto& c = reg.get<esengine::ecs::SegmentCollider>(entity);
@@ -2092,6 +2254,13 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
if (field == "enabled") { c.enabled = value; }
else { return false; }
return true;
+ } else if (comp == "SphereCollider3D") {
+ if (!reg.has<esengine::ecs::SphereCollider3D>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::SphereCollider3D>(entity);
+ if (field == "isSensor") { c.isSensor = value; }
+ else if (field == "enabled") { c.enabled = value; }
+ else { return false; }
+ return true;
} else if (comp == "SpineAnimation") {
if (!reg.has<esengine::ecs::SpineAnimation>(entity)) return false;
auto& c = reg.get<esengine::ecs::SpineAnimation>(entity);
@@ -2172,6 +2341,11 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
const auto& c = reg.get<esengine::ecs::BoxCollider>(entity);
if (field == "isSensor") { return c.isSensor; }
else if (field == "enabled") { return c.enabled; }
+ } else if (comp == "BoxCollider3D") {
+ if (!reg.has<esengine::ecs::BoxCollider3D>(entity)) return false;
+ const auto& c = reg.get<esengine::ecs::BoxCollider3D>(entity);
+ if (field == "isSensor") { return c.isSensor; }
+ else if (field == "enabled") { return c.enabled; }
} else if (comp == "Camera") {
if (!reg.has<esengine::ecs::Camera>(entity)) return false;
const auto& c = reg.get<esengine::ecs::Camera>(entity);
@@ -2182,6 +2356,11 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
const auto& c = reg.get<esengine::ecs::CapsuleCollider>(entity);
if (field == "isSensor") { return c.isSensor; }
else if (field == "enabled") { return c.enabled; }
+ } else if (comp == "CapsuleCollider3D") {
+ if (!reg.has<esengine::ecs::CapsuleCollider3D>(entity)) return false;
+ const auto& c = reg.get<esengine::ecs::CapsuleCollider3D>(entity);
+ if (field == "isSensor") { return c.isSensor; }
+ else if (field == "enabled") { return c.enabled; }
} else if (comp == "CircleCollider") {
if (!reg.has<esengine::ecs::CircleCollider>(entity)) return false;
const auto& c = reg.get<esengine::ecs::CircleCollider>(entity);
@@ -2233,6 +2412,11 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
if (field == "fixedRotation") { return c.fixedRotation; }
else if (field == "bullet") { return c.bullet; }
else if (field == "enabled") { return c.enabled; }
+ } else if (comp == "RigidBody3D") {
+ if (!reg.has<esengine::ecs::RigidBody3D>(entity)) return false;
+ const auto& c = reg.get<esengine::ecs::RigidBody3D>(entity);
+ if (field == "fixedRotation") { return c.fixedRotation; }
+ else if (field == "enabled") { return c.enabled; }
} else if (comp == "SegmentCollider") {
if (!reg.has<esengine::ecs::SegmentCollider>(entity)) return false;
const auto& c = reg.get<esengine::ecs::SegmentCollider>(entity);
@@ -2246,6 +2430,11 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
if (!reg.has<esengine::ecs::ShapeRenderer>(entity)) return false;
const auto& c = reg.get<esengine::ecs::ShapeRenderer>(entity);
if (field == "enabled") { return c.enabled; }
+ } else if (comp == "SphereCollider3D") {
+ if (!reg.has<esengine::ecs::SphereCollider3D>(entity)) return false;
+ const auto& c = reg.get<esengine::ecs::SphereCollider3D>(entity);
+ if (field == "isSensor") { return c.isSensor; }
+ else if (field == "enabled") { return c.enabled; }
} else if (comp == "SpineAnimation") {
if (!reg.has<esengine::ecs::SpineAnimation>(entity)) return false;
const auto& c = reg.get<esengine::ecs::SpineAnimation>(entity);
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index bf654d833..254906a69 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -24,6 +24,7 @@
#include "../ecs/components/ParticleEmitter.hpp"
#include "../ecs/components/ParticleForceField.hpp"
#include "../ecs/components/RigidBody.hpp"
+#include "../ecs/components/RigidBody3D.hpp"
#include "../ecs/components/ShadowCaster2D.hpp"
#include "../ecs/components/ShapeRenderer.hpp"
#include "../ecs/components/SpineAnimation.hpp"
@@ -805,6 +806,41 @@ RigidBodyJS rigidbodyToJS(const esengine::ecs::RigidBody& c) {
return js;
}
+struct RigidBody3DJS {
+ i32 bodyType;
+ f32 gravityScale;
+ f32 linearDamping;
+ f32 angularDamping;
+ bool fixedRotation;
+ bool enabled;
+};
+
+void rigidbody3dApplyJS(esengine::ecs::RigidBody3D& c, const RigidBody3DJS& js) {
+ c.bodyType = static_cast<BodyType>(js.bodyType);
+ c.gravityScale = js.gravityScale;
+ c.linearDamping = js.linearDamping;
+ c.angularDamping = js.angularDamping;
+ c.fixedRotation = js.fixedRotation;
+ c.enabled = js.enabled;
+}
+
+esengine::ecs::RigidBody3D rigidbody3dFromJS(const RigidBody3DJS& js) {
+ esengine::ecs::RigidBody3D c;
+ rigidbody3dApplyJS(c, js);
+ return c;
+}
+
+RigidBody3DJS rigidbody3dToJS(const esengine::ecs::RigidBody3D& c) {
+ RigidBody3DJS js;
+ js.bodyType = static_cast<i32>(c.bodyType);
+ js.gravityScale = c.gravityScale;
+ js.linearDamping = c.linearDamping;
+ js.angularDamping = c.angularDamping;
+ js.fixedRotation = c.fixedRotation;
+ js.enabled = c.enabled;
+ return js;
+}
+
struct SpriteJS {
u32 texture;
glm::vec4 color;
@@ -1207,6 +1243,13 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("categoryBits", &esengine::ecs::BoxCollider::categoryBits)
.field("maskBits", &esengine::ecs::BoxCollider::maskBits);
+ value_object<esengine::ecs::BoxCollider3D>("BoxCollider3D")
+ .field("halfExtents", &esengine::ecs::BoxCollider3D::halfExtents)
+ .field("friction", &esengine::ecs::BoxCollider3D::friction)
+ .field("restitution", &esengine::ecs::BoxCollider3D::restitution)
+ .field("isSensor", &esengine::ecs::BoxCollider3D::isSensor)
+ .field("enabled", &esengine::ecs::BoxCollider3D::enabled);
+
value_object<CameraJS>("Camera")
.field("projectionType", &CameraJS::projectionType)
.field("fov", &CameraJS::fov)
@@ -1241,6 +1284,14 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("categoryBits", &esengine::ecs::CapsuleCollider::categoryBits)
.field("maskBits", &esengine::ecs::CapsuleCollider::maskBits);
+ value_object<esengine::ecs::CapsuleCollider3D>("CapsuleCollider3D")
+ .field("radius", &esengine::ecs::CapsuleCollider3D::radius)
+ .field("halfHeight", &esengine::ecs::CapsuleCollider3D::halfHeight)
+ .field("friction", &esengine::ecs::CapsuleCollider3D::friction)
+ .field("restitution", &esengine::ecs::CapsuleCollider3D::restitution)
+ .field("isSensor", &esengine::ecs::CapsuleCollider3D::isSensor)
+ .field("enabled", &esengine::ecs::CapsuleCollider3D::enabled);
+
value_object<ChildrenJS>("Children")
.field("entities", &ChildrenJS::entities);
@@ -1397,6 +1448,14 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("bullet", &RigidBodyJS::bullet)
.field("enabled", &RigidBodyJS::enabled);
+ value_object<RigidBody3DJS>("RigidBody3D")
+ .field("bodyType", &RigidBody3DJS::bodyType)
+ .field("gravityScale", &RigidBody3DJS::gravityScale)
+ .field("linearDamping", &RigidBody3DJS::linearDamping)
+ .field("angularDamping", &RigidBody3DJS::angularDamping)
+ .field("fixedRotation", &RigidBody3DJS::fixedRotation)
+ .field("enabled", &RigidBody3DJS::enabled);
+
value_object<esengine::ecs::SegmentCollider>("SegmentCollider")
.field("point1", &esengine::ecs::SegmentCollider::point1)
.field("point2", &esengine::ecs::SegmentCollider::point2)
@@ -1421,6 +1480,13 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("parallax", &esengine::ecs::ShapeRenderer::parallax)
.field("enabled", &esengine::ecs::ShapeRenderer::enabled);
+ value_object<esengine::ecs::SphereCollider3D>("SphereCollider3D")
+ .field("radius", &esengine::ecs::SphereCollider3D::radius)
+ .field("friction", &esengine::ecs::SphereCollider3D::friction)
+ .field("restitution", &esengine::ecs::SphereCollider3D::restitution)
+ .field("isSensor", &esengine::ecs::SphereCollider3D::isSensor)
+ .field("enabled", &esengine::ecs::SphereCollider3D::enabled);
+
value_object<esengine::ecs::SpineAnimation>("SpineAnimation")
.field("skeletonPath", &esengine::ecs::SpineAnimation::skeletonPath)
.field("atlasPath", &esengine::ecs::SpineAnimation::atlasPath)
@@ -1620,6 +1686,27 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::BoxCollider>(entity);
}))
+ // BoxCollider3D
+ .function("hasBoxCollider3D", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::BoxCollider3D>(static_cast<Entity>(e));
+ }))
+ .function("getBoxCollider3D", optional_override([](Registry& r, u32 e) -> esengine::ecs::BoxCollider3D& {
+ auto entity = static_cast<Entity>(e);
+ static esengine::ecs::BoxCollider3D s_dummy{};
+ if (!r.valid(entity) || !r.has<esengine::ecs::BoxCollider3D>(entity)) return s_dummy;
+ return r.get<esengine::ecs::BoxCollider3D>(entity);
+ }), allow_raw_pointers())
+ .function("addBoxCollider3D", optional_override([](Registry& r, u32 e, const esengine::ecs::BoxCollider3D& c) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ r.emplaceOrReplace<esengine::ecs::BoxCollider3D>(entity, c);
+ }))
+ .function("removeBoxCollider3D", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::BoxCollider3D>(entity)) return;
+ r.remove<esengine::ecs::BoxCollider3D>(entity);
+ }))
+
// Camera
.function("hasCamera", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::Camera>(static_cast<Entity>(e));
@@ -1689,6 +1776,27 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::CapsuleCollider>(entity);
}))
+ // CapsuleCollider3D
+ .function("hasCapsuleCollider3D", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::CapsuleCollider3D>(static_cast<Entity>(e));
+ }))
+ .function("getCapsuleCollider3D", optional_override([](Registry& r, u32 e) -> esengine::ecs::CapsuleCollider3D& {
+ auto entity = static_cast<Entity>(e);
+ static esengine::ecs::CapsuleCollider3D s_dummy{};
+ if (!r.valid(entity) || !r.has<esengine::ecs::CapsuleCollider3D>(entity)) return s_dummy;
+ return r.get<esengine::ecs::CapsuleCollider3D>(entity);
+ }), allow_raw_pointers())
+ .function("addCapsuleCollider3D", optional_override([](Registry& r, u32 e, const esengine::ecs::CapsuleCollider3D& c) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ r.emplaceOrReplace<esengine::ecs::CapsuleCollider3D>(entity, c);
+ }))
+ .function("removeCapsuleCollider3D", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::CapsuleCollider3D>(entity)) return;
+ r.remove<esengine::ecs::CapsuleCollider3D>(entity);
+ }))
+
// Children
.function("hasChildren", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::Children>(static_cast<Entity>(e));
@@ -1962,6 +2070,30 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::RigidBody>(entity);
}))
+ // RigidBody3D
+ .function("hasRigidBody3D", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::RigidBody3D>(static_cast<Entity>(e));
+ }))
+ .function("getRigidBody3D", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::RigidBody3D>(entity)) return RigidBody3DJS{};
+ return rigidbody3dToJS(r.get<esengine::ecs::RigidBody3D>(entity));
+ }))
+ .function("addRigidBody3D", optional_override([](Registry& r, u32 e, const RigidBody3DJS& js) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ if (auto* existing = r.tryGet<esengine::ecs::RigidBody3D>(entity)) {
+ rigidbody3dApplyJS(*existing, js);
+ return;
+ }
+ r.emplaceOrReplace<esengine::ecs::RigidBody3D>(entity, rigidbody3dFromJS(js));
+ }))
+ .function("removeRigidBody3D", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::RigidBody3D>(entity)) return;
+ r.remove<esengine::ecs::RigidBody3D>(entity);
+ }))
+
// SegmentCollider
.function("hasSegmentCollider", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::SegmentCollider>(static_cast<Entity>(e));
@@ -2025,6 +2157,27 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::ShapeRenderer>(entity);
}))
+ // SphereCollider3D
+ .function("hasSphereCollider3D", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::SphereCollider3D>(static_cast<Entity>(e));
+ }))
+ .function("getSphereCollider3D", optional_override([](Registry& r, u32 e) -> esengine::ecs::SphereCollider3D& {
+ auto entity = static_cast<Entity>(e);
+ static esengine::ecs::SphereCollider3D s_dummy{};
+ if (!r.valid(entity) || !r.has<esengine::ecs::SphereCollider3D>(entity)) return s_dummy;
+ return r.get<esengine::ecs::SphereCollider3D>(entity);
+ }), allow_raw_pointers())
+ .function("addSphereCollider3D", optional_override([](Registry& r, u32 e, const esengine::ecs::SphereCollider3D& c) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ r.emplaceOrReplace<esengine::ecs::SphereCollider3D>(entity, c);
+ }))
+ .function("removeSphereCollider3D", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::SphereCollider3D>(entity)) return;
+ r.remove<esengine::ecs::SphereCollider3D>(entity);
+ }))
+
// SpineAnimation
.function("hasSpineAnimation", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::SpineAnimation>(static_cast<Entity>(e));
@@ -2297,9 +2450,11 @@ emscripten::val esengineGetBuiltinComponentNames() {
size_t i = 0;
arr.set(i++, val(std::string("BitmapText")));
arr.set(i++, val(std::string("BoxCollider")));
+ arr.set(i++, val(std::string("BoxCollider3D")));
arr.set(i++, val(std::string("Camera")));
arr.set(i++, val(std::string("Canvas")));
arr.set(i++, val(std::string("CapsuleCollider")));
+ arr.set(i++, val(std::string("CapsuleCollider3D")));
arr.set(i++, val(std::string("Children")));
arr.set(i++, val(std::string("CircleCollider")));
arr.set(i++, val(std::string("DragonBonesAnimation")));
@@ -2312,9 +2467,11 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("ParticleEmitter")));
arr.set(i++, val(std::string("ParticleForceField")));
arr.set(i++, val(std::string("RigidBody")));
+ arr.set(i++, val(std::string("RigidBody3D")));
arr.set(i++, val(std::string("SegmentCollider")));
arr.set(i++, val(std::string("ShadowCaster2D")));
arr.set(i++, val(std::string("ShapeRenderer")));
+ arr.set(i++, val(std::string("SphereCollider3D")));
arr.set(i++, val(std::string("SpineAnimation")));
arr.set(i++, val(std::string("Sprite")));
arr.set(i++, val(std::string("TilemapLayer")));
@@ -2357,6 +2514,11 @@ static_assert(offsetof(esengine::ecs::BoxCollider, isSensor) == 28, "ABI offset
static_assert(offsetof(esengine::ecs::BoxCollider, enabled) == 29, "ABI offset drift: esengine::ecs::BoxCollider.enabled (EHT expected 29)");
static_assert(offsetof(esengine::ecs::BoxCollider, categoryBits) == 32, "ABI offset drift: esengine::ecs::BoxCollider.categoryBits (EHT expected 32)");
static_assert(offsetof(esengine::ecs::BoxCollider, maskBits) == 36, "ABI offset drift: esengine::ecs::BoxCollider.maskBits (EHT expected 36)");
+static_assert(offsetof(esengine::ecs::BoxCollider3D, halfExtents) == 0, "ABI offset drift: esengine::ecs::BoxCollider3D.halfExtents (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::BoxCollider3D, friction) == 12, "ABI offset drift: esengine::ecs::BoxCollider3D.friction (EHT expected 12)");
+static_assert(offsetof(esengine::ecs::BoxCollider3D, restitution) == 16, "ABI offset drift: esengine::ecs::BoxCollider3D.restitution (EHT expected 16)");
+static_assert(offsetof(esengine::ecs::BoxCollider3D, isSensor) == 20, "ABI offset drift: esengine::ecs::BoxCollider3D.isSensor (EHT expected 20)");
+static_assert(offsetof(esengine::ecs::BoxCollider3D, enabled) == 21, "ABI offset drift: esengine::ecs::BoxCollider3D.enabled (EHT expected 21)");
static_assert(offsetof(esengine::ecs::Camera, projectionType) == 0, "ABI offset drift: esengine::ecs::Camera.projectionType (EHT expected 0)");
static_assert(offsetof(esengine::ecs::Camera, fov) == 4, "ABI offset drift: esengine::ecs::Camera.fov (EHT expected 4)");
static_assert(offsetof(esengine::ecs::Camera, orthoSize) == 8, "ABI offset drift: esengine::ecs::Camera.orthoSize (EHT expected 8)");
@@ -2385,6 +2547,12 @@ static_assert(offsetof(esengine::ecs::CapsuleCollider, isSensor) == 28, "ABI off
static_assert(offsetof(esengine::ecs::CapsuleCollider, enabled) == 29, "ABI offset drift: esengine::ecs::CapsuleCollider.enabled (EHT expected 29)");
static_assert(offsetof(esengine::ecs::CapsuleCollider, categoryBits) == 32, "ABI offset drift: esengine::ecs::CapsuleCollider.categoryBits (EHT expected 32)");
static_assert(offsetof(esengine::ecs::CapsuleCollider, maskBits) == 36, "ABI offset drift: esengine::ecs::CapsuleCollider.maskBits (EHT expected 36)");
+static_assert(offsetof(esengine::ecs::CapsuleCollider3D, radius) == 0, "ABI offset drift: esengine::ecs::CapsuleCollider3D.radius (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::CapsuleCollider3D, halfHeight) == 4, "ABI offset drift: esengine::ecs::CapsuleCollider3D.halfHeight (EHT expected 4)");
+static_assert(offsetof(esengine::ecs::CapsuleCollider3D, friction) == 8, "ABI offset drift: esengine::ecs::CapsuleCollider3D.friction (EHT expected 8)");
+static_assert(offsetof(esengine::ecs::CapsuleCollider3D, restitution) == 12, "ABI offset drift: esengine::ecs::CapsuleCollider3D.restitution (EHT expected 12)");
+static_assert(offsetof(esengine::ecs::CapsuleCollider3D, isSensor) == 16, "ABI offset drift: esengine::ecs::CapsuleCollider3D.isSensor (EHT expected 16)");
+static_assert(offsetof(esengine::ecs::CapsuleCollider3D, enabled) == 17, "ABI offset drift: esengine::ecs::CapsuleCollider3D.enabled (EHT expected 17)");
static_assert(offsetof(esengine::ecs::CircleCollider, radius) == 0, "ABI offset drift: esengine::ecs::CircleCollider.radius (EHT expected 0)");
static_assert(offsetof(esengine::ecs::CircleCollider, offset) == 4, "ABI offset drift: esengine::ecs::CircleCollider.offset (EHT expected 4)");
static_assert(offsetof(esengine::ecs::CircleCollider, density) == 12, "ABI offset drift: esengine::ecs::CircleCollider.density (EHT expected 12)");
@@ -2510,6 +2678,12 @@ static_assert(offsetof(esengine::ecs::RigidBody, angularDamping) == 12, "ABI off
static_assert(offsetof(esengine::ecs::RigidBody, fixedRotation) == 16, "ABI offset drift: esengine::ecs::RigidBody.fixedRotation (EHT expected 16)");
static_assert(offsetof(esengine::ecs::RigidBody, bullet) == 17, "ABI offset drift: esengine::ecs::RigidBody.bullet (EHT expected 17)");
static_assert(offsetof(esengine::ecs::RigidBody, enabled) == 18, "ABI offset drift: esengine::ecs::RigidBody.enabled (EHT expected 18)");
+static_assert(offsetof(esengine::ecs::RigidBody3D, bodyType) == 0, "ABI offset drift: esengine::ecs::RigidBody3D.bodyType (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::RigidBody3D, gravityScale) == 4, "ABI offset drift: esengine::ecs::RigidBody3D.gravityScale (EHT expected 4)");
+static_assert(offsetof(esengine::ecs::RigidBody3D, linearDamping) == 8, "ABI offset drift: esengine::ecs::RigidBody3D.linearDamping (EHT expected 8)");
+static_assert(offsetof(esengine::ecs::RigidBody3D, angularDamping) == 12, "ABI offset drift: esengine::ecs::RigidBody3D.angularDamping (EHT expected 12)");
+static_assert(offsetof(esengine::ecs::RigidBody3D, fixedRotation) == 16, "ABI offset drift: esengine::ecs::RigidBody3D.fixedRotation (EHT expected 16)");
+static_assert(offsetof(esengine::ecs::RigidBody3D, enabled) == 17, "ABI offset drift: esengine::ecs::RigidBody3D.enabled (EHT expected 17)");
static_assert(offsetof(esengine::ecs::SegmentCollider, point1) == 0, "ABI offset drift: esengine::ecs::SegmentCollider.point1 (EHT expected 0)");
static_assert(offsetof(esengine::ecs::SegmentCollider, point2) == 8, "ABI offset drift: esengine::ecs::SegmentCollider.point2 (EHT expected 8)");
static_assert(offsetof(esengine::ecs::SegmentCollider, density) == 16, "ABI offset drift: esengine::ecs::SegmentCollider.density (EHT expected 16)");
@@ -2528,6 +2702,11 @@ static_assert(offsetof(esengine::ecs::ShapeRenderer, cornerRadius) == 28, "ABI o
static_assert(offsetof(esengine::ecs::ShapeRenderer, layer) == 32, "ABI offset drift: esengine::ecs::ShapeRenderer.layer (EHT expected 32)");
static_assert(offsetof(esengine::ecs::ShapeRenderer, parallax) == 36, "ABI offset drift: esengine::ecs::ShapeRenderer.parallax (EHT expected 36)");
static_assert(offsetof(esengine::ecs::ShapeRenderer, enabled) == 44, "ABI offset drift: esengine::ecs::ShapeRenderer.enabled (EHT expected 44)");
+static_assert(offsetof(esengine::ecs::SphereCollider3D, radius) == 0, "ABI offset drift: esengine::ecs::SphereCollider3D.radius (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::SphereCollider3D, friction) == 4, "ABI offset drift: esengine::ecs::SphereCollider3D.friction (EHT expected 4)");
+static_assert(offsetof(esengine::ecs::SphereCollider3D, restitution) == 8, "ABI offset drift: esengine::ecs::SphereCollider3D.restitution (EHT expected 8)");
+static_assert(offsetof(esengine::ecs::SphereCollider3D, isSensor) == 12, "ABI offset drift: esengine::ecs::SphereCollider3D.isSensor (EHT expected 12)");
+static_assert(offsetof(esengine::ecs::SphereCollider3D, enabled) == 13, "ABI offset drift: esengine::ecs::SphereCollider3D.enabled (EHT expected 13)");
static_assert(offsetof(esengine::ecs::SpineAnimation, timeScale) == 48, "ABI offset drift: esengine::ecs::SpineAnimation.timeScale (EHT expected 48)");
static_assert(offsetof(esengine::ecs::SpineAnimation, loop) == 52, "ABI offset drift: esengine::ecs::SpineAnimation.loop (EHT expected 52)");
static_assert(offsetof(esengine::ecs::SpineAnimation, playing) == 53, "ABI offset drift: esengine::ecs::SpineAnimation.playing (EHT expected 53)");
@@ -2642,7 +2821,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "65f6ac377586cd75";
+static const char* kEsAbiLayoutHash = "fb8d63de6b3e9865";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
index d4a42d76c..771d28f40 100644
--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp
@@ -57,17 +57,36 @@ ObjectLayer layerOf(EMotionType motion) {
return motion == EMotionType::Static ? Layers::STATIC : Layers::MOVING;
}
+/// What a body is beyond its shape: how it answers to gravity, how it slows, and
+/// whether the solver may turn it. Passed as one record because every add takes
+/// the same set and a fourth positional float each would be unreadable.
+struct BodyMotion {
+ int motion = 0;
+ float gravityScale = 1.0f;
+ float linearDamping = 0.0f;
+ float angularDamping = 0.0f;
+ int fixedRotation = 0;
+};
+
/// Register a shape as a body, and remember which entity it speaks for.
uint32_t addBody(uint32_t entity, Shape* shape, float px, float py, float pz,
- float qx, float qy, float qz, float qw, int motion,
+ float qx, float qy, float qz, float qw, const BodyMotion& how,
float friction, float restitution, int isSensor) {
if (!g().isValid()) return 0;
- const EMotionType motionType = motionTypeOf(motion);
+ const EMotionType motionType = motionTypeOf(how.motion);
BodyCreationSettings settings(shape, RVec3(px, py, pz), Quat(qx, qy, qz, qw).Normalized(),
motionType, layerOf(motionType));
settings.mFriction = friction;
settings.mRestitution = restitution;
settings.mIsSensor = isSensor != 0;
+ settings.mGravityFactor = how.gravityScale;
+ settings.mLinearDamping = how.linearDamping;
+ settings.mAngularDamping = how.angularDamping;
+ // What keeps a character upright: the solver may move it and never turn it.
+ if (how.fixedRotation != 0) {
+ settings.mAllowedDOFs = EAllowedDOFs::TranslationX | EAllowedDOFs::TranslationY
+ | EAllowedDOFs::TranslationZ;
+ }
BodyInterface& bodies = g().system->GetBodyInterface();
const BodyID id = bodies.CreateAndAddBody(
settings, motionType == EMotionType::Static ? EActivation::DontActivate
@@ -164,18 +183,24 @@ EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addBox(uint32_t entity, float hx, float hy, float hz,
float px, float py, float pz,
float qx, float qy, float qz, float qw,
- int motion, float friction, float restitution, int isSensor) {
+ int motion, float gravityScale, float linearDamping,
+ float angularDamping, int fixedRotation,
+ float friction, float restitution, int isSensor) {
return addBody(entity, new BoxShape(Vec3(hx, hy, hz)), px, py, pz, qx, qy, qz, qw,
- motion, friction, restitution, isSensor);
+ {motion, gravityScale, linearDamping, angularDamping, fixedRotation},
+ friction, restitution, isSensor);
}
EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addSphere(uint32_t entity, float radius,
float px, float py, float pz,
float qx, float qy, float qz, float qw,
- int motion, float friction, float restitution, int isSensor) {
+ int motion, float gravityScale, float linearDamping,
+ float angularDamping, int fixedRotation,
+ float friction, float restitution, int isSensor) {
return addBody(entity, new SphereShape(radius), px, py, pz, qx, qy, qz, qw,
- motion, friction, restitution, isSensor);
+ {motion, gravityScale, linearDamping, angularDamping, fixedRotation},
+ friction, restitution, isSensor);
}
/// `halfHeight` is the cylinder half-height, so the capsule is `2*halfHeight + 2*radius`
@@ -184,9 +209,12 @@ EMSCRIPTEN_KEEPALIVE
uint32_t physics3d_addCapsule(uint32_t entity, float radius, float halfHeight,
float px, float py, float pz,
float qx, float qy, float qz, float qw,
- int motion, float friction, float restitution, int isSensor) {
+ int motion, float gravityScale, float linearDamping,
+ float angularDamping, int fixedRotation,
+ float friction, float restitution, int isSensor) {
return addBody(entity, new CapsuleShape(halfHeight, radius), px, py, pz, qx, qy, qz, qw,
- motion, friction, restitution, isSensor);
+ {motion, gravityScale, linearDamping, angularDamping, fixedRotation},
+ friction, restitution, isSensor);
}
EMSCRIPTEN_KEEPALIVE
diff --git a/src/esengine/ecs/components/RigidBody3D.hpp b/src/esengine/ecs/components/RigidBody3D.hpp
new file mode 100644
index 000000000..14a018cde
--- /dev/null
+++ b/src/esengine/ecs/components/RigidBody3D.hpp
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file RigidBody3D.hpp
+ * @brief A body the 3D world simulates, and the shapes that give it extent.
+ * @details Its own components rather than a third dimension bolted onto the 2D
+ * ones: a 2D scene keeps the solver, the units and the feel it already
+ * has, and pays nothing for a world it never asks for. A scene picks one
+ * of the two — an entity carrying both is served by the 2D one, which was
+ * there first.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+#include "../../math/Math.hpp"
+#include "./RigidBody.hpp"
+
+namespace esengine::ecs {
+
+/**
+ * @brief A body in the 3D world.
+ *
+ * @code
+ * auto& body = registry.emplace<RigidBody3D>(e);
+ * body.bodyType = BodyType::Dynamic;
+ * @endcode
+ */
+ES_COMPONENT()
+struct RigidBody3D {
+ /** @brief Static never moves, Kinematic is moved by hand, Dynamic is solved. */
+ ES_PROPERTY(enum=BodyType)
+ BodyType bodyType{BodyType::Dynamic};
+
+ /** @brief Scales this body's share of the world's gravity. 0 = weightless. */
+ ES_PROPERTY(min=0)
+ f32 gravityScale{1.0f};
+
+ ES_PROPERTY(min=0)
+ f32 linearDamping{0.05f};
+
+ ES_PROPERTY(min=0)
+ f32 angularDamping{0.05f};
+
+ /** @brief Keeps the body upright: the solver may move it, never turn it. What a
+ * character on legs wants, and what a crate does not. */
+ ES_PROPERTY()
+ bool fixedRotation{false};
+
+ /** @brief Disabled bodies are left out of the world entirely. */
+ ES_PROPERTY()
+ bool enabled{true};
+};
+
+/** @brief An axis-aligned box, sized in world units around the entity's origin. */
+ES_COMPONENT()
+struct BoxCollider3D {
+ ES_PROPERTY()
+ glm::vec3 halfExtents{0.5f, 0.5f, 0.5f};
+
+ ES_PROPERTY(min=0)
+ f32 friction{0.3f};
+
+ ES_PROPERTY(min=0, max=1)
+ f32 restitution{0.0f};
+
+ /** @brief A sensor reports overlaps and stops nothing. */
+ ES_PROPERTY()
+ bool isSensor{false};
+
+ ES_PROPERTY()
+ bool enabled{true};
+};
+
+ES_COMPONENT()
+struct SphereCollider3D {
+ ES_PROPERTY(min=0)
+ f32 radius{0.5f};
+
+ ES_PROPERTY(min=0)
+ f32 friction{0.3f};
+
+ ES_PROPERTY(min=0, max=1)
+ f32 restitution{0.0f};
+
+ ES_PROPERTY()
+ bool isSensor{false};
+
+ ES_PROPERTY()
+ bool enabled{true};
+};
+
+/**
+ * @brief An upright capsule — the shape a character is.
+ * @details Total height is `2*(halfHeight + radius)`: @ref halfHeight is the
+ * cylinder's half, and a cap of @ref radius sits on each end. Stated
+ * because the two are easy to swap and their SUM still holds a body at
+ * the same height, so a swap shows up only in how wide it is.
+ */
+ES_COMPONENT()
+struct CapsuleCollider3D {
+ ES_PROPERTY(min=0)
+ f32 radius{0.3f};
+
+ ES_PROPERTY(min=0)
+ f32 halfHeight{0.5f};
+
+ ES_PROPERTY(min=0)
+ f32 friction{0.3f};
+
+ ES_PROPERTY(min=0, max=1)
+ f32 restitution{0.0f};
+
+ ES_PROPERTY()
+ bool isSensor{false};
+
+ ES_PROPERTY()
+ bool enabled{true};
+};
+
+} // namespace esengine::ecs