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.

fix(physics): a polygon collider is drawn as the polygon it collides as

yhhd354b87860f5
diff --git a/desktop b/desktop
index b935d2cd8..0d31482e1 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit b935d2cd84e3c6ec6d01cef24fbab55e389c1edb
+Subproject commit 0d31482e14b52c5ae3bec420e732daf0b18fd0d2
diff --git a/docs/astro/src/content/docs/gameplay/physics.mdx b/docs/astro/src/content/docs/gameplay/physics.mdx
index f3cd103e7..c804b07e8 100644
--- a/docs/astro/src/content/docs/gameplay/physics.mdx
+++ b/docs/astro/src/content/docs/gameplay/physics.mdx
@@ -115,9 +115,40 @@ are in meters.
| `CircleCollider2D` | `radius` (`0.5`). |
| `CapsuleCollider2D` | `radius`, `halfHeight`. |
| `SegmentCollider2D` | `point1`, `point2` (a one-sided edge). |
-| `PolygonCollider2D` | `vertices: Vec2[]`, `radius` (rounded). |
+| `PolygonCollider2D` | `vertices: Vec2[]` (convex, at most 8), `radius` (rounded). |
| `ChainCollider2D` | `points: Vec2[]`, `isLoop` (static edge chain; no `density`/`isSensor`). |
+#### Polygons are convex, and hold eight vertices
+
+A `PolygonCollider2D` collides as the **convex hull** of its vertices. Author a
+notch and the solver fills it in: nothing can enter the dent, because in the
+physics world the dent is not there. Box2D stores at most **8** vertices per
+polygon, and a vertex welded onto its neighbour or sitting flat on the edge its
+neighbours already span is dropped as well.
+
+The editor does not hide this. Whatever the solver declined — the filled-in
+notch, the ninth vertex — is drawn as a dashed amber outline beside the solid
+one, in the viewport gizmo and in the runtime debug draw alike. A solid outline
+is what collides; a dashed one is what you drew.
+
+For **concave static geometry** — terrain, cave walls, the inside of a bowl — use
+a `ChainCollider2D` instead. A chain is a run of edges, so it can be as concave
+as you like. It is level geometry, though, not a body's shape: it has no
+`density` or `isSensor`, and its points are not rebuilt while the game runs.
+
+For a **concave moving body**, neither answers on its own: split the shape into
+convex pieces. One entity carries one collider of each type, and every collider
+on it becomes a shape on the same body — so a box plus a polygon covers the
+simple cases. Anything more wants child entities with their own bodies, joined.
+
+#### Editing vertices in the viewport
+
+Select the entity and the collider's points become handles. Drag one to move it,
+**click a point to delete it**, and **click the hollow handle on an edge** to
+insert a vertex there and drag it into place — one gesture, one undo step. An
+edit the solver would refuse (a polygon below 3 points or above 8, a chain below
+4) is refused in the editor too, and says which limit it hit.
+
## Collision filtering
![Project Settings → Physics — collision layer names and the collision matrix](@/assets/guides/en/collision-matrix.png)
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx
index 995ff4c7f..9c137e846 100644
--- a/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx
@@ -107,9 +107,36 @@ const spawnBall = defineSystem([Commands()], (cmds) => {
| `CircleCollider2D` | `radius`(`0.5`)。 |
| `CapsuleCollider2D` | `radius`、`halfHeight`。 |
| `SegmentCollider2D` | `point1`、`point2`(单边)。 |
-| `PolygonCollider2D` | `vertices: Vec2[]`、`radius`(圆角)。 |
+| `PolygonCollider2D` | `vertices: Vec2[]`(凸多边形,最多 8 个)、`radius`(圆角)。 |
| `ChainCollider2D` | `points: Vec2[]`、`isLoop`(静态边链;无 `density`/`isSensor`)。 |
+#### 多边形是凸的,而且只装得下八个顶点
+
+`PolygonCollider2D` 按顶点的**凸包**碰撞。你画一个凹口,求解器会把它填平:
+东西进不去那个凹口,因为在物理世界里那个凹口根本不存在。Box2D 每个
+多边形最多存 **8** 个顶点;被拖到邻居身上的顶点、或正好落在邻居连线上的
+顶点,也同样会被丢掉。
+
+编辑器不会瞒着你。求解器不要的那部分——被填平的凹口、第九个顶点
+——会在实线轮廓旁边画成橙色虚线,视口 Gizmo 和运行时调试绘制都一样。
+实线是**真能撞到的**,虚线是**你画的**。
+
+**凹的静态地形**——地表、洞穴内壁、碗的内侧——请改用 `ChainCollider2D`。
+链是一串边,要多凹都行。但它是关卡几何,不是刚体的形状:没有 `density`
+和 `isSensor`,而且运行中不会重建它的点。
+
+**会动的凹形物体**两者都不够:要把形状拆成几块凸的。一个实体每种碰撞体
+只能挂一个,但它身上所有碰撞体都会变成同一个刚体的形状——所以“盒子 +
+多边形”能覆盖简单情况。再复杂就要用子实体各自带刚体,再用关节连起来。
+
+#### 在视口里改顶点
+
+选中实体,碰撞体的点就变成手柄。拖动移动,**点击一个点就删掉它**,
+**点击边上那个空心手柄**则在那里插入一个顶点并直接拖到位——一个手势,
+一步撤销。求解器会拒绝的编辑(多边形少于 3 个或多于 8 个、链少于 4 个),
+编辑器同样拒绝,并会说清楚撞到的是哪条限制。
+
+
## 碰撞过滤
![项目设置 → 物理——碰撞层名字与碰撞矩阵](@/assets/guides/zh/collision-matrix.png)
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 5bd7eef20..76fb72a50 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 113,
"beta": 99,
- "experimental": 1831,
+ "experimental": 1837,
"deprecated": 3
},
- "total": 2043,
+ "total": 2049,
"subsystems": [
{
"id": "ecs",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index fa153bff3..769f0e412 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 92 beta · 1670 experimental · 3 deprecated
+Symbols: 113 public · 92 beta · 1676 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2197,6 +2197,7 @@ shape: Collider2DShape
## Collider2DOutline — interface @experimental
```
circles: { c: Vec2; r: number; }[]
+declined: Vec2[][] | undefined
polylines: Vec2[][]
```
@@ -4757,11 +4758,26 @@ Restart = 1
"1.0"
```
+## MAX_POLYGON_VERTICES — const @experimental
+```
+8
+```
+
## MESH_MAX_BONES — const @experimental
```
64
```
+## MIN_CHAIN_POINTS — const @experimental
+```
+4
+```
+
+## MIN_POLYGON_VERTICES — const @experimental
+```
+3
+```
+
## ManifestModel — class @experimental
```
allAssets: () => AddressableManifestAsset[]
@@ -6367,6 +6383,13 @@ enabled: boolean
ComponentDef<PolygonCollider2DData>
```
+## PolygonHullDiff — interface @experimental
+```
+declined: number
+hull: Vec2[]
+overflow: number
+```
+
## PooledAudioNode — interface @experimental
```
gain: GainNode
@@ -11054,6 +11077,11 @@ BtPlugin
(baseOrthoSize: number, designAspect: number, actualAspect: number, scaleMode: number, matchWidthOrHeight: number): number
```
+## computePolygonHull — function @experimental
+```
+(vertices: readonly Vec2[]): Vec2[]
+```
+
## computeStreaming — function @experimental
```
(cells: readonly StreamCell[], focusX: number, focusY: number, loadRadius: number, unloadRadius: number, active: ReadonlySet<string>, focusZ?: number): StreamDecision
@@ -12664,6 +12692,11 @@ PerceptionPlugin
(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean
```
+## polygonHullDiff — function @experimental
+```
+(vertices: readonly Vec2[]): PolygonHullDiff
+```
+
## postProcessPlugin — const @experimental
```
PostProcessPlugin
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 41b6c6652..f5fef76ae 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 97 beta · 1689 experimental · 3 deprecated
+Symbols: 113 public · 97 beta · 1695 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -2197,6 +2197,7 @@ shape: Collider2DShape
## Collider2DOutline — interface @experimental
```
circles: { c: Vec2; r: number; }[]
+declined: Vec2[][] | undefined
polylines: Vec2[][]
```
@@ -4765,11 +4766,26 @@ Restart = 1
"1.0"
```
+## MAX_POLYGON_VERTICES — const @experimental
+```
+8
+```
+
## MESH_MAX_BONES — const @experimental
```
64
```
+## MIN_CHAIN_POINTS — const @experimental
+```
+4
+```
+
+## MIN_POLYGON_VERTICES — const @experimental
+```
+3
+```
+
## ManifestModel — class @experimental
```
allAssets: () => AddressableManifestAsset[]
@@ -6550,6 +6566,13 @@ enabled: boolean
ComponentDef<PolygonCollider2DData>
```
+## PolygonHullDiff — interface @experimental
+```
+declined: number
+hull: Vec2[]
+overflow: number
+```
+
## PooledAudioNode — interface @experimental
```
gain: GainNode
@@ -11262,6 +11285,11 @@ BtPlugin
(baseOrthoSize: number, designAspect: number, actualAspect: number, scaleMode: number, matchWidthOrHeight: number): number
```
+## computePolygonHull — function @experimental
+```
+(vertices: readonly Vec2[]): Vec2[]
+```
+
## computeStreaming — function @experimental
```
(cells: readonly StreamCell[], focusX: number, focusY: number, loadRadius: number, unloadRadius: number, active: ReadonlySet<string>, focusZ?: number): StreamDecision
@@ -12907,6 +12935,11 @@ PerceptionPlugin
(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean
```
+## polygonHullDiff — function @experimental
+```
+(vertices: readonly Vec2[]): PolygonHullDiff
+```
+
## postProcessPlugin — const @experimental
```
PostProcessPlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index c6681318c..fb3c934fd 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 94 beta · 1669 experimental · 3 deprecated
+Symbols: 113 public · 94 beta · 1675 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2192,6 +2192,7 @@ shape: Collider2DShape
## Collider2DOutline — interface @experimental
```
circles: { c: Vec2; r: number; }[]
+declined: Vec2[][] | undefined
polylines: Vec2[][]
```
@@ -4752,11 +4753,26 @@ Restart = 1
"1.0"
```
+## MAX_POLYGON_VERTICES — const @experimental
+```
+8
+```
+
## MESH_MAX_BONES — const @experimental
```
64
```
+## MIN_CHAIN_POINTS — const @experimental
+```
+4
+```
+
+## MIN_POLYGON_VERTICES — const @experimental
+```
+3
+```
+
## ManifestModel — class @experimental
```
allAssets: () => AddressableManifestAsset[]
@@ -6362,6 +6378,13 @@ enabled: boolean
ComponentDef<PolygonCollider2DData>
```
+## PolygonHullDiff — interface @experimental
+```
+declined: number
+hull: Vec2[]
+overflow: number
+```
+
## PooledAudioNode — interface @experimental
```
gain: GainNode
@@ -11049,6 +11072,11 @@ BtPlugin
(baseOrthoSize: number, designAspect: number, actualAspect: number, scaleMode: number, matchWidthOrHeight: number): number
```
+## computePolygonHull — function @experimental
+```
+(vertices: readonly Vec2[]): Vec2[]
+```
+
## computeStreaming — function @experimental
```
(cells: readonly StreamCell[], focusX: number, focusY: number, loadRadius: number, unloadRadius: number, active: ReadonlySet<string>, focusZ?: number): StreamDecision
@@ -12669,6 +12697,11 @@ PerceptionPlugin
(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean
```
+## polygonHullDiff — function @experimental
+```
+(vertices: readonly Vec2[]): PolygonHullDiff
+```
+
## postProcessPlugin — const @experimental
```
PostProcessPlugin
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 64fd69b71..fc5301734 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 92 beta · 1691 experimental · 3 deprecated
+Symbols: 113 public · 92 beta · 1697 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2192,6 +2192,7 @@ shape: Collider2DShape
## Collider2DOutline — interface @experimental
```
circles: { c: Vec2; r: number; }[]
+declined: Vec2[][] | undefined
polylines: Vec2[][]
```
@@ -4752,11 +4753,26 @@ Restart = 1
"1.0"
```
+## MAX_POLYGON_VERTICES — const @experimental
+```
+8
+```
+
## MESH_MAX_BONES — const @experimental
```
64
```
+## MIN_CHAIN_POINTS — const @experimental
+```
+4
+```
+
+## MIN_POLYGON_VERTICES — const @experimental
+```
+3
+```
+
## ManifestModel — class @experimental
```
allAssets: () => AddressableManifestAsset[]
@@ -6608,6 +6624,13 @@ enabled: boolean
ComponentDef<PolygonCollider2DData>
```
+## PolygonHullDiff — interface @experimental
+```
+declined: number
+hull: Vec2[]
+overflow: number
+```
+
## PooledAudioNode — interface @experimental
```
gain: GainNode
@@ -11301,6 +11324,11 @@ BtPlugin
(baseOrthoSize: number, designAspect: number, actualAspect: number, scaleMode: number, matchWidthOrHeight: number): number
```
+## computePolygonHull — function @experimental
+```
+(vertices: readonly Vec2[]): Vec2[]
+```
+
## computeStreaming — function @experimental
```
(cells: readonly StreamCell[], focusX: number, focusY: number, loadRadius: number, unloadRadius: number, active: ReadonlySet<string>, focusZ?: number): StreamDecision
@@ -12926,6 +12954,11 @@ PerceptionPlugin
(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean
```
+## polygonHullDiff — function @experimental
+```
+(vertices: readonly Vec2[]): PolygonHullDiff
+```
+
## postProcessPlugin — const @experimental
```
PostProcessPlugin
diff --git a/sdk/etc/physics.api.md b/sdk/etc/physics.api.md
index fb08544e8..35b458b46 100644
--- a/sdk/etc/physics.api.md
+++ b/sdk/etc/physics.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/physics
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 0 public · 5 beta · 63 experimental · 0 deprecated
+Symbols: 0 public · 5 beta · 69 experimental · 0 deprecated
## BodyType — enum @experimental
```
@@ -119,6 +119,7 @@ shape: Collider2DShape
## Collider2DOutline — interface @experimental
```
circles: { c: Vec2; r: number; }[]
+declined: Vec2[][] | undefined
polylines: Vec2[][]
```
@@ -215,6 +216,21 @@ motorSpeed: number
upperAngle: number
```
+## MAX_POLYGON_VERTICES — const @experimental
+```
+8
+```
+
+## MIN_CHAIN_POINTS — const @experimental
+```
+4
+```
+
+## MIN_POLYGON_VERTICES — const @experimental
+```
+3
+```
+
## MassData — interface @experimental
```
centerOfMass: Vec2
@@ -577,6 +593,13 @@ restitution: number
vertices: Vec2[]
```
+## PolygonHullDiff — interface @experimental
+```
+declined: number
+hull: Vec2[]
+overflow: number
+```
+
## RaycastHit — interface @experimental
```
entity: number
@@ -695,6 +718,11 @@ upperTranslation: number
(shape: Collider2DShape, center: Vec2, angle: number, ppu: number): Collider2DOutline
```
+## computePolygonHull — function @experimental
+```
+(vertices: readonly Vec2[]): Vec2[]
+```
+
## drawPhysics2DDebug — function @experimental
```
(app: App, physicsApiRes: ResourceDef<VelocityProvider>, physicsEventsRes: ResourceDef<Physics2DEventsData>): void
@@ -715,6 +743,11 @@ upperTranslation: number
(wasmUrl: string, config?: Physics2DPluginConfig, factory?: PhysicsModuleFactory): Physics2DPlugin
```
+## polygonHullDiff — function @experimental
+```
+(vertices: readonly Vec2[]): PolygonHullDiff
+```
+
## readCollider2DShapes — function @experimental
```
(world: World, entity: number): Collider2DInstance[]
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 3f6750c44..d7521c4c0 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 92 beta · 1681 experimental · 3 deprecated
+Symbols: 113 public · 92 beta · 1687 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -2192,6 +2192,7 @@ shape: Collider2DShape
## Collider2DOutline — interface @experimental
```
circles: { c: Vec2; r: number; }[]
+declined: Vec2[][] | undefined
polylines: Vec2[][]
```
@@ -4759,11 +4760,26 @@ Restart = 1
"1.0"
```
+## MAX_POLYGON_VERTICES — const @experimental
+```
+8
+```
+
## MESH_MAX_BONES — const @experimental
```
64
```
+## MIN_CHAIN_POINTS — const @experimental
+```
+4
+```
+
+## MIN_POLYGON_VERTICES — const @experimental
+```
+3
+```
+
## ManifestModel — class @experimental
```
allAssets: () => AddressableManifestAsset[]
@@ -6369,6 +6385,13 @@ enabled: boolean
ComponentDef<PolygonCollider2DData>
```
+## PolygonHullDiff — interface @experimental
+```
+declined: number
+hull: Vec2[]
+overflow: number
+```
+
## PooledAudioNode — interface @experimental
```
gain: GainNode
@@ -11077,6 +11100,11 @@ BtPlugin
(baseOrthoSize: number, designAspect: number, actualAspect: number, scaleMode: number, matchWidthOrHeight: number): number
```
+## computePolygonHull — function @experimental
+```
+(vertices: readonly Vec2[]): Vec2[]
+```
+
## computeStreaming — function @experimental
```
(cells: readonly StreamCell[], focusX: number, focusY: number, loadRadius: number, unloadRadius: number, active: ReadonlySet<string>, focusZ?: number): StreamDecision
@@ -12692,6 +12720,11 @@ PerceptionPlugin
(px: number, py: number, worldX: number, worldY: number, worldW: number, worldH: number, pivotX: number, pivotY: number): boolean
```
+## polygonHullDiff — function @experimental
+```
+(vertices: readonly Vec2[]): PolygonHullDiff
+```
+
## postProcessPlugin — const @experimental
```
PostProcessPlugin
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.ts
index 43e530898..975912f14 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -179,11 +179,20 @@ export {
shapeCenter,
collider2DOutline,
CAPSULE_ARC_SEGMENTS,
+ MIN_CHAIN_POINTS,
type Collider2DShape,
type Collider2DInstance,
type Collider2DOutline,
} from './physics/ColliderShape2D';
+export {
+ computePolygonHull,
+ polygonHullDiff,
+ MAX_POLYGON_VERTICES,
+ MIN_POLYGON_VERTICES,
+ type PolygonHullDiff,
+} from './physics/polygonHull2D';
+
export {
RigidBody3D,
BoxCollider3D,
diff --git a/sdk/src/physics/ColliderShape2D.ts b/sdk/src/physics/ColliderShape2D.ts
index c4e7d05e4..871431941 100644
--- a/sdk/src/physics/ColliderShape2D.ts
+++ b/sdk/src/physics/ColliderShape2D.ts
@@ -23,10 +23,14 @@ import type {
BoxCollider2DData, CircleCollider2DData, CapsuleCollider2DData,
SegmentCollider2DData, PolygonCollider2DData, ChainCollider2DData,
} from './PhysicsComponents';
+import { computePolygonHull } from './polygonHull2D';
/** Semicircle-cap segment count for a capsule outline (matches the legacy debug draw). */
export const CAPSULE_ARC_SEGMENTS = 16;
+/** Box2D builds no chain below four points; the editor may not author one either. */
+export const MIN_CHAIN_POINTS = 4;
+
/** A collider's geometry, in physics metres. Offset (box/circle/capsule) is metres too;
* segment/polygon/chain carry their points directly and sit at the entity origin. */
export type Collider2DShape =
@@ -52,6 +56,13 @@ export interface Collider2DInstance {
export interface Collider2DOutline {
polylines: Vec2[][];
circles: { c: Vec2; r: number }[];
+ /**
+ * The authored outline where the solver does not have it — a concave polygon's
+ * filled-in notch, or vertices past the eight Box2D takes. Absent when what was
+ * drawn is what collides; every backend strokes it apart, or the viewport says
+ * a shape exists where nothing can be hit.
+ */
+ declined?: Vec2[][];
}
const ZERO: Vec2 = { x: 0, y: 0 };
@@ -120,8 +131,16 @@ export function collider2DOutline(shape: Collider2DShape, center: Vec2, angle: n
circles: [],
};
case 'polygon': {
- const p = shape.vertices.map((v) => w(v.x * ppu, v.y * ppu));
- return { polylines: p.length > 0 ? [[...p, p[0]]] : [], circles: [] };
+ const ring = (vs: readonly Vec2[]): Vec2[][] => {
+ const p = vs.map((v) => w(v.x * ppu, v.y * ppu));
+ return p.length > 0 ? [[...p, p[0]]] : [];
+ };
+ // A hull as long as the ring carries every authored vertex, since a hull
+ // is a subset of what it was given: equal counts mean nothing was welded,
+ // truncated or filled in, so the authored ring IS the solver's polygon.
+ const hull = computePolygonHull(shape.vertices);
+ if (hull.length === shape.vertices.length) return { polylines: ring(shape.vertices), circles: [] };
+ return { polylines: ring(hull), circles: [], declined: ring(shape.vertices) };
}
case 'chain': {
const p = shape.points.map((v) => w(v.x * ppu, v.y * ppu));
diff --git a/sdk/src/physics/Physics2DDebugDraw.ts b/sdk/src/physics/Physics2DDebugDraw.ts
index 78d91675c..010f51c2a 100644
--- a/sdk/src/physics/Physics2DDebugDraw.ts
+++ b/sdk/src/physics/Physics2DDebugDraw.ts
@@ -37,6 +37,8 @@ const KINEMATIC_COLOR: Color = { r: 0.2, g: 1.0, b: 1.0, a: 0.7 };
const SENSOR_COLOR: Color = { r: 1.0, g: 1.0, b: 0.2, a: 0.5 };
const VELOCITY_COLOR: Color = { r: 1.0, g: 0.2, b: 0.2, a: 0.8 };
const CONTACT_COLOR: Color = { r: 1.0, g: 0.2, b: 0.2, a: 1.0 };
+/** The outline the solver declined — drawn faintly, in the colour of a mistake. */
+const DECLINED_COLOR: Color = { r: 1.0, g: 0.35, b: 0.1, a: 0.45 };
const DEBUG_LINE_THICKNESS = 1.5;
const CONTACT_POINT_RADIUS = 3;
const VELOCITY_SCALE = 0.5;
@@ -133,6 +135,14 @@ export function drawPhysics2DDebug(
for (const circ of outline.circles) {
Draw.circleOutline(circ.c, circ.r, color, DEBUG_LINE_THICKNESS, CIRCLE_SEGMENTS);
}
+ // What was authored past what collides: a concave polygon's filled-in
+ // notch. Without it the overlay draws a hull nobody wrote and reads as
+ // the collider having moved.
+ for (const pl of outline.declined ?? []) {
+ for (let i = 0; i + 1 < pl.length; i++) {
+ Draw.line(pl[i], pl[i + 1], DECLINED_COLOR, DEBUG_LINE_THICKNESS);
+ }
+ }
}
}
diff --git a/sdk/src/physics/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.ts
index ee53493c5..eb7c34a19 100644
--- a/sdk/src/physics/PhysicsSystem.ts
+++ b/sdk/src/physics/PhysicsSystem.ts
@@ -30,6 +30,8 @@ import {
type DistanceJoint2DData, type SliderJoint2DData, type FixedJoint2DData, type WheelJoint2DData,
type MotorJoint2DData,
} from './PhysicsComponents';
+import { MAX_POLYGON_VERTICES } from './polygonHull2D';
+import { MIN_CHAIN_POINTS } from './ColliderShape2D';
import {
Physics2DEvents,
COLLISION_EVENT_STRIDE,
@@ -148,7 +150,7 @@ export function addShapeForEntity(
const category = poly.categoryBits ?? 0x0001;
const mask = resolveCollisionMask(category, poly.maskBits ?? 0xFFFF, layerMasks);
const verts = poly.vertices;
- const count = Math.min(verts.length, 8);
+ const count = Math.min(verts.length, MAX_POLYGON_VERTICES);
const byteSize = count * 2 * 4;
withMalloc(module, byteSize, ptr => {
const base = ptr >> 2;
@@ -167,7 +169,7 @@ export function addShapeForEntity(
const chain = activeCollider(world, entity, ChainCollider2D) as ChainCollider2DData | null;
if (chain) {
const pts = chain.points;
- if (pts.length < 4) return;
+ if (pts.length < MIN_CHAIN_POINTS) return;
const byteSize = pts.length * 2 * 4;
withMalloc(module, byteSize, ptr => {
const base = ptr >> 2;
diff --git a/sdk/src/physics/index.ts b/sdk/src/physics/index.ts
index dd38cc923..9967e18bf 100644
--- a/sdk/src/physics/index.ts
+++ b/sdk/src/physics/index.ts
@@ -86,11 +86,20 @@ export {
shapeCenter,
collider2DOutline,
CAPSULE_ARC_SEGMENTS,
+ MIN_CHAIN_POINTS,
type Collider2DShape,
type Collider2DInstance,
type Collider2DOutline,
} from './ColliderShape2D';
+export {
+ computePolygonHull,
+ polygonHullDiff,
+ MAX_POLYGON_VERTICES,
+ MIN_POLYGON_VERTICES,
+ type PolygonHullDiff,
+} from './polygonHull2D';
+
export {
CharacterController2D,
moveAndSlide,
diff --git a/sdk/src/physics/polygonHull2D.ts b/sdk/src/physics/polygonHull2D.ts
new file mode 100644
index 000000000..4a8ada35f
--- /dev/null
+++ b/sdk/src/physics/polygonHull2D.ts
@@ -0,0 +1,167 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file polygonHull2D.ts
+ * @brief The polygon Box2D actually builds from a PolygonCollider2D's vertices.
+ *
+ * @details A PolygonCollider2D is authored as a vertex ring and collides as the
+ * CONVEX HULL of that ring: a notch is filled in, welded and collinear
+ * points are dropped, and a ring the hull rejects makes no shape at all.
+ * Concavity is Box2D's constraint, not a choice this engine can revisit.
+ *
+ * So the authored ring is not a drawable answer to "what collides here".
+ * This is a port of `b2ComputeHull` (third_party/box2d/src/hull.c) kept
+ * faithful to its welding and collinear slop, because its whole job is
+ * AGREEMENT: the gizmo, the debug draw and the solver must name one
+ * polygon, including the vertices it silently declines.
+ *
+ * Units are physics metres — the slop below is metres, so a hull
+ * computed in pixels would weld at a thousand times the real tolerance.
+ */
+import type { Vec2 } from '../types';
+
+/**
+ * The most vertices Box2D stores in one polygon (`B2_MAX_POLYGON_VERTICES`).
+ * Authoring past it is not an error anyone reports: the extra vertices are
+ * dropped before the hull is computed.
+ */
+export const MAX_POLYGON_VERTICES = 8;
+
+/** Fewer than a triangle is not a polygon: Box2D builds no shape from it. */
+export const MIN_POLYGON_VERTICES = 3;
+
+/** `B2_LINEAR_SLOP`, at the engine's length unit of one metre per metre. */
+const LINEAR_SLOP = 0.005;
+
+const cross = (a: Vec2, b: Vec2): number => a.x * b.y - a.y * b.x;
+const sub = (a: Vec2, b: Vec2): Vec2 => ({ x: a.x - b.x, y: a.y - b.y });
+const distSq = (a: Vec2, b: Vec2): number => (a.x - b.x) ** 2 + (a.y - b.y) ** 2;
+
+function normalize(v: Vec2): Vec2 {
+ const len = Math.hypot(v.x, v.y);
+ return len > 0 ? { x: v.x / len, y: v.y / len } : { x: 0, y: 0 };
+}
+
+/** Quickhull's recursion: the hull of `ps` strictly right of the edge p1→p2. */
+function recurseHull(p1: Vec2, p2: Vec2, ps: readonly Vec2[]): Vec2[] {
+ if (ps.length === 0) return [];
+ const e = normalize(sub(p2, p1));
+
+ const right: Vec2[] = [];
+ let best = 0;
+ let bestDistance = cross(sub(ps[0], p1), e);
+ if (bestDistance > 0) right.push(ps[0]);
+ for (let i = 1; i < ps.length; i++) {
+ const d = cross(sub(ps[i], p1), e);
+ if (d > bestDistance) {
+ best = i;
+ bestDistance = d;
+ }
+ if (d > 0) right.push(ps[i]);
+ }
+ if (bestDistance < 2 * LINEAR_SLOP) return [];
+
+ const apex = ps[best];
+ return [...recurseHull(p1, apex, right), apex, ...recurseHull(apex, p2, right)];
+}
+
+/**
+ * The convex hull Box2D builds from `vertices`, counter-clockwise, in metres.
+ * Empty when Box2D builds no shape: fewer than three vertices survive welding,
+ * or every surviving one is collinear.
+ */
+export function computePolygonHull(vertices: readonly Vec2[]): Vec2[] {
+ if (vertices.length < MIN_POLYGON_VERTICES) return [];
+ const points = vertices.slice(0, MAX_POLYGON_VERTICES);
+
+ // Aggressive welding, first point winning, exactly as the solver does it: a
+ // vertex dragged onto its neighbour vanishes from the shape rather than
+ // narrowing it.
+ const tolSq = 16 * LINEAR_SLOP * LINEAR_SLOP;
+ let lower = { x: Infinity, y: Infinity };
+ let upper = { x: -Infinity, y: -Infinity };
+ const ps: Vec2[] = [];
+ for (const v of points) {
+ lower = { x: Math.min(lower.x, v.x), y: Math.min(lower.y, v.y) };
+ upper = { x: Math.max(upper.x, v.x), y: Math.max(upper.y, v.y) };
+ if (!ps.some((q) => distSq(v, q) < tolSq)) ps.push(v);
+ }
+ if (ps.length < MIN_POLYGON_VERTICES) return [];
+
+ // The two seeds: the point furthest from the AABB centre, then the point
+ // furthest from that one. Each leaves the working set by swapping in its last
+ // member, which is what fixes the order the rest is split in.
+ const centre = { x: (lower.x + upper.x) / 2, y: (lower.y + upper.y) / 2 };
+ let f = 0;
+ for (let i = 1; i < ps.length; i++) if (distSq(centre, ps[i]) > distSq(centre, ps[f])) f = i;
+ const p1 = ps[f];
+ ps[f] = ps[ps.length - 1];
+ ps.pop();
+
+ f = 0;
+ for (let i = 1; i < ps.length; i++) if (distSq(p1, ps[i]) > distSq(p1, ps[f])) f = i;
+ const p2 = ps[f];
+ ps[f] = ps[ps.length - 1];
+ ps.pop();
+
+ const e = normalize(sub(p2, p1));
+ const right: Vec2[] = [];
+ const left: Vec2[] = [];
+ for (const v of ps) {
+ const d = cross(sub(v, p1), e);
+ if (d >= 2 * LINEAR_SLOP) right.push(v);
+ else if (d <= -2 * LINEAR_SLOP) left.push(v);
+ }
+
+ const above = recurseHull(p1, p2, right);
+ const below = recurseHull(p2, p1, left);
+ if (above.length === 0 && below.length === 0) return [];
+
+ const hull = [p1, ...above, p2, ...below];
+ return mergeCollinear(hull);
+}
+
+/** Drop every vertex its two neighbours already span, until none is left. */
+function mergeCollinear(hull: Vec2[]): Vec2[] {
+ for (let searching = true; searching && hull.length > 2;) {
+ searching = false;
+ for (let i = 0; i < hull.length; i++) {
+ const s1 = hull[i];
+ const s2 = hull[(i + 1) % hull.length];
+ const s3 = hull[(i + 2) % hull.length];
+ if (cross(sub(s2, s1), normalize(sub(s3, s1))) <= 2 * LINEAR_SLOP) {
+ hull.splice((i + 1) % hull.length, 1);
+ searching = true;
+ break;
+ }
+ }
+ }
+ return hull;
+}
+
+/** What a polygon collider's authored ring loses on its way to the solver. */
+export interface PolygonHullDiff {
+ /** The hull the solver collides with, counter-clockwise. Empty = no shape. */
+ hull: Vec2[];
+ /** Authored vertices past {@link MAX_POLYGON_VERTICES}, never offered to it. */
+ overflow: number;
+ /** Offered vertices the hull declines: a notch filled in, a weld, a collinear run. */
+ declined: number;
+}
+
+/**
+ * What was authored against what collides, so a caller can say which of the two
+ * it is drawing. The ways a vertex fails to reach the solver are counted apart
+ * because only one of them is the author's arithmetic; they look alike on screen.
+ */
+export function polygonHullDiff(vertices: readonly Vec2[]): PolygonHullDiff {
+ const hull = computePolygonHull(vertices);
+ const offered = Math.min(vertices.length, MAX_POLYGON_VERTICES);
+ return {
+ hull,
+ overflow: vertices.length - offered,
+ // An empty hull is no shape at all, not a hull missing vertices — the
+ // louder fact, and counting it here would read as a milder one.
+ declined: hull.length > 0 ? offered - hull.length : 0,
+ };
+}
diff --git a/sdk/tests/polygon-hull.test.ts b/sdk/tests/polygon-hull.test.ts
new file mode 100644
index 000000000..0b63d0314
--- /dev/null
+++ b/sdk/tests/polygon-hull.test.ts
@@ -0,0 +1,146 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file polygon-hull.test.ts — the TS hull against the one Box2D builds.
+ *
+ * Every expectation here was MEASURED by calling `b2ComputeHull` itself, not
+ * derived from reading it: a probe linking third_party/box2d/src/hull.c, core.c
+ * and math_functions.c was fed these exact rings and its output pasted in. A
+ * port whose only job is agreement has to be checked against the thing it agrees
+ * with, so re-measure the same way if Box2D moves under us.
+ *
+ * Stitch ORDER is asserted too, not just the point set. The decagon's is the one
+ * that would catch a hull rewritten as a monotone chain: quickhull leaves it in
+ * an order no angular sweep produces, and a shape drawn in another order is a
+ * different shape.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ computePolygonHull, polygonHullDiff, MAX_POLYGON_VERTICES,
+} from '../src/physics/polygonHull2D';
+import { collider2DOutline, type Collider2DShape } from '../src/physics/ColliderShape2D';
+
+type P = { x: number; y: number };
+const p = (x: number, y: number): P => ({ x, y });
+
+const expectRing = (got: readonly P[], want: readonly [number, number][]) => {
+ expect(got).toHaveLength(want.length);
+ want.forEach(([x, y], i) => {
+ expect(got[i].x).toBeCloseTo(x, 5);
+ expect(got[i].y).toBeCloseTo(y, 5);
+ });
+};
+
+describe('computePolygonHull — measured against b2ComputeHull', () => {
+ it('keeps a convex ring whole, in the order it was given', () => {
+ expectRing(
+ computePolygonHull([p(-0.5, -0.5), p(0.5, -0.5), p(0.5, 0.5), p(-0.5, 0.5)]),
+ [[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]],
+ );
+ });
+
+ it('fills in a concave notch — the dart loses the vertex pointing inward', () => {
+ expectRing(
+ computePolygonHull([p(-1, -1), p(0, 0), p(1, -1), p(0, 1)]),
+ [[-1, -1], [1, -1], [0, 1]],
+ );
+ });
+
+ it('fills in an L — the inner corner is not a hull vertex', () => {
+ expectRing(
+ computePolygonHull([p(0, 0), p(2, 0), p(2, 1), p(1, 1), p(1, 2), p(0, 2)]),
+ [[0, 0], [2, 0], [2, 1], [1, 2], [0, 2]],
+ );
+ });
+
+ it('drops a vertex sitting on the edge its neighbours already span', () => {
+ expectRing(
+ computePolygonHull([p(0, 0), p(1, 0), p(2, 0), p(2, 2), p(0, 2)]),
+ [[0, 0], [2, 0], [2, 2], [0, 2]],
+ );
+ });
+
+ it('welds a vertex dragged onto its neighbour rather than narrowing the shape', () => {
+ expectRing(
+ computePolygonHull([p(0, 0), p(0.001, 0), p(1, 0), p(1, 1)]),
+ [[0, 0], [1, 0], [1, 1]],
+ );
+ });
+
+ it('builds NO shape from a ring with no area, or from fewer than three points', () => {
+ expect(computePolygonHull([p(0, 0), p(1, 0), p(2, 0)])).toEqual([]);
+ expect(computePolygonHull([p(0, 0), p(1, 0)])).toEqual([]);
+ expect(computePolygonHull([])).toEqual([]);
+ });
+
+ it('takes a star down to the four points that enclose it', () => {
+ expectRing(
+ computePolygonHull([
+ p(0, 1), p(0.2, 0.2), p(1, 0), p(0.2, -0.2),
+ p(0, -1), p(-0.2, -0.2), p(-1, 0), p(-0.2, 0.2),
+ ]),
+ [[0, 1], [-1, 0], [0, -1], [1, 0]],
+ );
+ });
+
+ it('stitches in quickhull order, which no angular sweep would produce', () => {
+ const ring = Array.from({ length: MAX_POLYGON_VERTICES }, (_, i) => {
+ const a = (i * 6.2831853) / 10;
+ return p(Math.fround(Math.cos(a)), Math.fround(Math.sin(a)));
+ });
+ expectRing(computePolygonHull(ring), [
+ [0.309017, 0.951057], [-0.309017, 0.951057], [-0.809017, 0.587785], [-1, 0],
+ [-0.809017, -0.587785], [-0.309017, -0.951057], [1, 0], [0.809017, 0.587785],
+ ]);
+ });
+
+ it('never offers the solver more vertices than it stores', () => {
+ const ring = Array.from({ length: 12 }, (_, i) => {
+ const a = (i * 2 * Math.PI) / 12;
+ return p(Math.cos(a), Math.sin(a));
+ });
+ expect(computePolygonHull(ring).length).toBeLessThanOrEqual(MAX_POLYGON_VERTICES);
+ expect(polygonHullDiff(ring).overflow).toBe(12 - MAX_POLYGON_VERTICES);
+ });
+});
+
+describe('polygonHullDiff', () => {
+ it('counts nothing lost when the ring is already convex', () => {
+ const d = polygonHullDiff([p(-0.5, -0.5), p(0.5, -0.5), p(0.5, 0.5), p(-0.5, 0.5)]);
+ expect(d.overflow).toBe(0);
+ expect(d.declined).toBe(0);
+ });
+
+ it('counts the notch the hull declines', () => {
+ expect(polygonHullDiff([p(-1, -1), p(0, 0), p(1, -1), p(0, 1)]).declined).toBe(1);
+ });
+
+ it('reports an empty hull as no shape, not as a hull short of vertices', () => {
+ const d = polygonHullDiff([p(0, 0), p(1, 0), p(2, 0)]);
+ expect(d.hull).toEqual([]);
+ expect(d.declined).toBe(0);
+ });
+});
+
+describe('collider2DOutline draws what collides', () => {
+ const outlineOf = (vertices: P[]) =>
+ collider2DOutline({ kind: 'polygon', vertices } as Collider2DShape, p(0, 0), 0, 100);
+
+ it('a convex polygon draws once — nothing was declined', () => {
+ const o = outlineOf([p(-0.5, -0.5), p(0.5, -0.5), p(0.5, 0.5), p(-0.5, 0.5)]);
+ expect(o.declined).toBeUndefined();
+ expect(o.polylines[0]).toHaveLength(5); // 4 corners + the closing point
+ });
+
+ it('a concave polygon draws the hull solid and the authored ring apart', () => {
+ const o = outlineOf([p(-1, -1), p(0, 0), p(1, -1), p(0, 1)]);
+ expect(o.polylines[0]).toHaveLength(4); // 3 hull corners + closing
+ expect(o.declined?.[0]).toHaveLength(5); // 4 authored corners + closing
+ });
+
+ it('a ring that builds no shape draws no solid outline at all', () => {
+ const o = outlineOf([p(0, 0), p(1, 0), p(2, 0)]);
+ expect(o.polylines).toEqual([]);
+ expect(o.declined?.[0]).toHaveLength(4);
+ });
+});