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 polygon collider takes any ring, concave and unbounded

yhhe121426d2907
diff --git a/desktop b/desktop
index 0d31482e1..9c17c5f76 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 0d31482e14b52c5ae3bec420e732daf0b18fd0d2
+Subproject commit 9c17c5f7625a54360e2058cd2a42379a18254f17
diff --git a/docs/astro/src/content/docs/gameplay/physics.mdx b/docs/astro/src/content/docs/gameplay/physics.mdx
index c804b07e8..704be6f62 100644
--- a/docs/astro/src/content/docs/gameplay/physics.mdx
+++ b/docs/astro/src/content/docs/gameplay/physics.mdx
@@ -115,39 +115,42 @@ are in meters.
| `CircleCollider2D` | `radius` (`0.5`). |
| `CapsuleCollider2D` | `radius`, `halfHeight`. |
| `SegmentCollider2D` | `point1`, `point2` (a one-sided edge). |
-| `PolygonCollider2D` | `vertices: Vec2[]` (convex, at most 8), `radius` (rounded). |
+| `PolygonCollider2D` | `vertices: Vec2[]` (any shape, concave allowed), `radius` (rounded). |
| `ChainCollider2D` | `points: Vec2[]`, `isLoop` (static edge chain; no `density`/`isSensor`). |
-#### Polygons are convex, and hold eight vertices
+#### Concave polygons, and how many vertices you may draw
-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.
+`PolygonCollider2D.vertices` takes as many points as you like, in any shape,
+concave included. Box2D itself builds only CONVEX polygons of at most 8 vertices,
+so a ring that is neither is split into convex pieces and each piece becomes its
+own shape on the same body. The cap belongs to a piece, not to what you draw.
-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.
+Pieces behave as one collider: mass sums over them the way it does over any two
+colliders on a body, and a contact with any piece is a contact with the entity.
+The cost is real, though — each piece is a shape in the broadphase — so a
+400-point outline is 400 points' worth of work, not one polygon's.
-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.
+Two things a divided polygon cannot do:
-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.
+- **`radius`** (rounded corners) rounds the OUTER boundary, and a cut between two
+ pieces is not boundary. It applies only when the ring stays in one piece.
+- **A ring that crosses itself** has no partition at all. It falls back to the
+ convex hull, and the editor draws the authored ring beside it as a dashed amber
+ outline so the difference is visible without playing the scene. A solid outline
+ is what collides; a dashed one is what you drew.
+
+A `ChainCollider2D` is still the better answer for long static edge geometry —
+terrain, cave walls — where nothing needs the inside to be solid. A chain is a run
+of edges: no `density`, no `isSensor`, and its points are not rebuilt while the
+game runs, but it costs one shape however long it is.
#### 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.
+insert a vertex there and drag it into place — one gesture, one undo step. The
+floors below which the solver builds nothing (3 points for a polygon, 4 for a
+chain) are refused in the editor too, and say which limit they hit.
## Collision filtering
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 9c137e846..3b1c32995 100644
--- a/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx
@@ -107,36 +107,39 @@ const spawnBall = defineSystem([Commands()], (cmds) => {
| `CircleCollider2D` | `radius`(`0.5`)。 |
| `CapsuleCollider2D` | `radius`、`halfHeight`。 |
| `SegmentCollider2D` | `point1`、`point2`(单边)。 |
-| `PolygonCollider2D` | `vertices: Vec2[]`(凸多边形,最多 8 个)、`radius`(圆角)。 |
+| `PolygonCollider2D` | `vertices: Vec2[]`(任意形状,可以是凹的)、`radius`(圆角)。 |
| `ChainCollider2D` | `points: Vec2[]`、`isLoop`(静态边链;无 `density`/`isSensor`)。 |
-#### 多边形是凸的,而且只装得下八个顶点
+#### 凹多边形,以及你能画多少个顶点
-`PolygonCollider2D` 按顶点的**凸包**碰撞。你画一个凹口,求解器会把它填平:
-东西进不去那个凹口,因为在物理世界里那个凹口根本不存在。Box2D 每个
-多边形最多存 **8** 个顶点;被拖到邻居身上的顶点、或正好落在邻居连线上的
-顶点,也同样会被丢掉。
+`PolygonCollider2D.vertices` 想画多少点就画多少,什么形状都行,包括凹的。
+Box2D 本身只能做最多 8 个顶点的**凸**多边形,所以不满足这两条的轮廓
+会被拆成若干凸块,每块在同一个刚体上各成一个形状。那个上限属于**一块**,
+不属于你画的东西。
-编辑器不会瞒着你。求解器不要的那部分——被填平的凹口、第九个顶点
-——会在实线轮廓旁边画成橙色虚线,视口 Gizmo 和运行时调试绘制都一样。
-实线是**真能撞到的**,虚线是**你画的**。
+拆出来的块行为上是一个碰撞体:质量像同一刚体上的任意两个碰撞体那样相加,
+碰到任一块就是碰到这个实体。但开销是真的——每块都是宽相里的一个形状——
+所以 400 个点的轮廓就是 400 个点的开销,不是一个多边形的。
-**凹的静态地形**——地表、洞穴内壁、碗的内侧——请改用 `ChainCollider2D`。
-链是一串边,要多凹都行。但它是关卡几何,不是刚体的形状:没有 `density`
-和 `isSensor`,而且运行中不会重建它的点。
+被拆开的多边形有两件事做不了:
-**会动的凹形物体**两者都不够:要把形状拆成几块凸的。一个实体每种碰撞体
-只能挂一个,但它身上所有碰撞体都会变成同一个刚体的形状——所以“盒子 +
-多边形”能覆盖简单情况。再复杂就要用子实体各自带刚体,再用关节连起来。
+- **`radius`**(圆角)磨的是**外边界**,而两块之间的切缝不是边界。
+ 只有轮廓没被拆开时它才生效。
+- **自交叉的轮廓**根本不存在划分。它会退回凸包,并且编辑器会把你画的轮廓
+ 在旁边画成橙色虚线,不用运行就能看出差在哪里。实线是**真能撞到的**,
+ 虚线是**你画的**。
+
+对于长的静态边界几何——地表、洞穴内壁——`ChainCollider2D` 仍然更合适,
+只要没人需要它里面是实心的。链是一串边:没有 `density`、没有 `isSensor`,
+运行中也不重建它的点,但不管多长都只算一个形状。
#### 在视口里改顶点
选中实体,碰撞体的点就变成手柄。拖动移动,**点击一个点就删掉它**,
**点击边上那个空心手柄**则在那里插入一个顶点并直接拖到位——一个手势,
-一步撤销。求解器会拒绝的编辑(多边形少于 3 个或多于 8 个、链少于 4 个),
+一步撤销。低于求解器建不出形状的下限(多边形 3 个点、链 4 个),
编辑器同样拒绝,并会说清楚撞到的是哪条限制。
-
## 碰撞过滤
![项目设置 → 物理——碰撞层名字与碰撞矩阵](@/assets/guides/zh/collision-matrix.png)
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 769f0e412..0d3ba5e20 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -6383,11 +6383,10 @@ enabled: boolean
ComponentDef<PolygonCollider2DData>
```
-## PolygonHullDiff — interface @experimental
+## PolygonDecomposition — interface @experimental
```
-declined: number
-hull: Vec2[]
-overflow: number
+degenerate: boolean
+pieces: readonly Vec2[][]
```
## PooledAudioNode — interface @experimental
@@ -11297,6 +11296,11 @@ Plugin
(blob: string): DecodedChunk[]
```
+## decomposePolygon2D — function @experimental
+```
+(vertices: readonly Vec2[]): PolygonDecomposition
+```
+
## defaultFrameStats — function @experimental
```
(): FrameStats
@@ -12692,11 +12696,6 @@ 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 f5fef76ae..745734d8f 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -6566,11 +6566,10 @@ enabled: boolean
ComponentDef<PolygonCollider2DData>
```
-## PolygonHullDiff — interface @experimental
+## PolygonDecomposition — interface @experimental
```
-declined: number
-hull: Vec2[]
-overflow: number
+degenerate: boolean
+pieces: readonly Vec2[][]
```
## PooledAudioNode — interface @experimental
@@ -11530,6 +11529,11 @@ Plugin
(blob: string): DecodedChunk[]
```
+## decomposePolygon2D — function @experimental
+```
+(vertices: readonly Vec2[]): PolygonDecomposition
+```
+
## defaultFrameStats — function @experimental
```
(): FrameStats
@@ -12935,11 +12939,6 @@ 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 fb3c934fd..2696119a1 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -6378,11 +6378,10 @@ enabled: boolean
ComponentDef<PolygonCollider2DData>
```
-## PolygonHullDiff — interface @experimental
+## PolygonDecomposition — interface @experimental
```
-declined: number
-hull: Vec2[]
-overflow: number
+degenerate: boolean
+pieces: readonly Vec2[][]
```
## PooledAudioNode — interface @experimental
@@ -11292,6 +11291,11 @@ Plugin
(blob: string): DecodedChunk[]
```
+## decomposePolygon2D — function @experimental
+```
+(vertices: readonly Vec2[]): PolygonDecomposition
+```
+
## defaultFrameStats — function @experimental
```
(): FrameStats
@@ -12697,11 +12701,6 @@ 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 fc5301734..2974816c8 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -6624,11 +6624,10 @@ enabled: boolean
ComponentDef<PolygonCollider2DData>
```
-## PolygonHullDiff — interface @experimental
+## PolygonDecomposition — interface @experimental
```
-declined: number
-hull: Vec2[]
-overflow: number
+degenerate: boolean
+pieces: readonly Vec2[][]
```
## PooledAudioNode — interface @experimental
@@ -11549,6 +11548,11 @@ Plugin
(blob: string): DecodedChunk[]
```
+## decomposePolygon2D — function @experimental
+```
+(vertices: readonly Vec2[]): PolygonDecomposition
+```
+
## defaultFrameStats — function @experimental
```
(): FrameStats
@@ -12954,11 +12958,6 @@ 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 35b458b46..a00696fcd 100644
--- a/sdk/etc/physics.api.md
+++ b/sdk/etc/physics.api.md
@@ -593,11 +593,10 @@ restitution: number
vertices: Vec2[]
```
-## PolygonHullDiff — interface @experimental
+## PolygonDecomposition — interface @experimental
```
-declined: number
-hull: Vec2[]
-overflow: number
+degenerate: boolean
+pieces: readonly Vec2[][]
```
## RaycastHit — interface @experimental
@@ -723,6 +722,11 @@ upperTranslation: number
(vertices: readonly Vec2[]): Vec2[]
```
+## decomposePolygon2D — function @experimental
+```
+(vertices: readonly Vec2[]): PolygonDecomposition
+```
+
## drawPhysics2DDebug — function @experimental
```
(app: App, physicsApiRes: ResourceDef<VelocityProvider>, physicsEventsRes: ResourceDef<Physics2DEventsData>): void
@@ -743,11 +747,6 @@ 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 d7521c4c0..264f43a75 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -6385,11 +6385,10 @@ enabled: boolean
ComponentDef<PolygonCollider2DData>
```
-## PolygonHullDiff — interface @experimental
+## PolygonDecomposition — interface @experimental
```
-declined: number
-hull: Vec2[]
-overflow: number
+degenerate: boolean
+pieces: readonly Vec2[][]
```
## PooledAudioNode — interface @experimental
@@ -11320,6 +11319,11 @@ Plugin
(blob: string): DecodedChunk[]
```
+## decomposePolygon2D — function @experimental
+```
+(vertices: readonly Vec2[]): PolygonDecomposition
+```
+
## defaultFrameStats — function @experimental
```
(): FrameStats
@@ -12720,11 +12724,6 @@ 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 975912f14..3c5135d54 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -187,12 +187,15 @@ export {
export {
computePolygonHull,
- polygonHullDiff,
MAX_POLYGON_VERTICES,
MIN_POLYGON_VERTICES,
- type PolygonHullDiff,
} from './physics/polygonHull2D';
+export {
+ decomposePolygon2D,
+ type PolygonDecomposition,
+} from './physics/polygonDecompose2D';
+
export {
RigidBody3D,
BoxCollider3D,
diff --git a/sdk/src/physics/ColliderShape2D.ts b/sdk/src/physics/ColliderShape2D.ts
index 871431941..8df4b09b0 100644
--- a/sdk/src/physics/ColliderShape2D.ts
+++ b/sdk/src/physics/ColliderShape2D.ts
@@ -23,7 +23,7 @@ import type {
BoxCollider2DData, CircleCollider2DData, CapsuleCollider2DData,
SegmentCollider2DData, PolygonCollider2DData, ChainCollider2DData,
} from './PhysicsComponents';
-import { computePolygonHull } from './polygonHull2D';
+import { decomposePolygon2D } from './polygonDecompose2D';
/** Semicircle-cap segment count for a capsule outline (matches the legacy debug draw). */
export const CAPSULE_ARC_SEGMENTS = 16;
@@ -135,12 +135,17 @@ export function collider2DOutline(shape: Collider2DShape, center: Vec2, angle: n
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) };
+ // The ring is the collision boundary whenever it can be partitioned, and
+ // the pieces behind it are how that boundary is built rather than a
+ // different shape — so a concave collider draws as one outline, once.
+ const { pieces, degenerate } = decomposePolygon2D(shape.vertices);
+ if (!degenerate && pieces.length > 0) return { polylines: ring(shape.vertices), circles: [] };
+ // It crosses itself, or has no area: what collides is not what was drawn.
+ return {
+ polylines: pieces.flatMap((piece) => ring(piece)),
+ 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/PhysicsSystem.ts b/sdk/src/physics/PhysicsSystem.ts
index eb7c34a19..686239e3c 100644
--- a/sdk/src/physics/PhysicsSystem.ts
+++ b/sdk/src/physics/PhysicsSystem.ts
@@ -30,7 +30,7 @@ import {
type DistanceJoint2DData, type SliderJoint2DData, type FixedJoint2DData, type WheelJoint2DData,
type MotorJoint2DData,
} from './PhysicsComponents';
-import { MAX_POLYGON_VERTICES } from './polygonHull2D';
+import { decomposePolygon2D } from './polygonDecompose2D';
import { MIN_CHAIN_POINTS } from './ColliderShape2D';
import {
Physics2DEvents,
@@ -149,21 +149,29 @@ export function addShapeForEntity(
if (poly) {
const category = poly.categoryBits ?? 0x0001;
const mask = resolveCollisionMask(category, poly.maskBits ?? 0xFFFF, layerMasks);
- const verts = poly.vertices;
- const count = Math.min(verts.length, MAX_POLYGON_VERTICES);
- const byteSize = count * 2 * 4;
- withMalloc(module, byteSize, ptr => {
- const base = ptr >> 2;
- for (let i = 0; i < count; i++) {
- module.HEAPF32[base + i * 2] = verts[i].x;
- module.HEAPF32[base + i * 2 + 1] = verts[i].y;
- }
- module._physics_addPolygonShape(
- entity, ptr, count, poly.radius ?? 0,
- poly.density, poly.friction, poly.restitution, poly.isSensor ? 1 : 0,
- category, mask
- );
- });
+ // Box2D takes only convex polygons, and only eight vertices of one, so an
+ // authored ring becomes as many shapes as it needs. They share the body,
+ // and density sums over them the way it does over any two colliders.
+ const { pieces } = decomposePolygon2D(poly.vertices);
+ // A corner radius rounds the BOUNDARY, and a cut between two pieces is not
+ // boundary: rounding each piece would bulge the shape outward along every
+ // seam. Only an undivided polygon can carry it.
+ const radius = pieces.length === 1 ? (poly.radius ?? 0) : 0;
+ for (const piece of pieces) {
+ const byteSize = piece.length * 2 * 4;
+ withMalloc(module, byteSize, ptr => {
+ const base = ptr >> 2;
+ for (let i = 0; i < piece.length; i++) {
+ module.HEAPF32[base + i * 2] = piece[i].x;
+ module.HEAPF32[base + i * 2 + 1] = piece[i].y;
+ }
+ module._physics_addPolygonShape(
+ entity, ptr, piece.length, radius,
+ poly.density, poly.friction, poly.restitution, poly.isSensor ? 1 : 0,
+ category, mask
+ );
+ });
+ }
}
const chain = activeCollider(world, entity, ChainCollider2D) as ChainCollider2DData | null;
diff --git a/sdk/src/physics/index.ts b/sdk/src/physics/index.ts
index 9967e18bf..1a7e56667 100644
--- a/sdk/src/physics/index.ts
+++ b/sdk/src/physics/index.ts
@@ -94,12 +94,15 @@ export {
export {
computePolygonHull,
- polygonHullDiff,
MAX_POLYGON_VERTICES,
MIN_POLYGON_VERTICES,
- type PolygonHullDiff,
} from './polygonHull2D';
+export {
+ decomposePolygon2D,
+ type PolygonDecomposition,
+} from './polygonDecompose2D';
+
export {
CharacterController2D,
moveAndSlide,
diff --git a/sdk/src/physics/polygonDecompose2D.ts b/sdk/src/physics/polygonDecompose2D.ts
new file mode 100644
index 000000000..42e9e73d1
--- /dev/null
+++ b/sdk/src/physics/polygonDecompose2D.ts
@@ -0,0 +1,271 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file polygonDecompose2D.ts
+ * @brief The convex pieces a concave collider ring collides as.
+ *
+ * @details Box2D builds only convex polygons, and only eight vertices of one. A
+ * ring that is neither is not a shape it can take — but it IS a union of
+ * shapes it can take, so the limit belongs to a PIECE rather than to
+ * what an author may draw.
+ *
+ * Ear clipping to triangles, then merging neighbours back while the
+ * result stays convex and within the cap. The merge works on vertex
+ * INDICES, so two pieces share an edge exactly rather than within a
+ * tolerance: float comparison at a seam is how a partition develops
+ * gaps nothing can be pushed out of.
+ *
+ * Every piece is finally passed through {@link computePolygonHull},
+ * which is what Box2D will do to it. A sliver the solver would refuse
+ * is dropped here instead of silently becoming no shape at run time.
+ */
+import type { Vec2 } from '../types';
+import { computePolygonHull, MAX_POLYGON_VERTICES, MIN_POLYGON_VERTICES } from './polygonHull2D';
+
+/** Points nearer than this are one point, matching the hull's own welding. */
+const WELD = 0.02;
+
+const cross = (ax: number, ay: number, bx: number, by: number): number => ax * by - ay * bx;
+
+/** The turn at `b` walking a → b → c. Positive is a left turn, so convex in CCW. */
+function turn(a: Vec2, b: Vec2, c: Vec2): number {
+ return cross(b.x - a.x, b.y - a.y, c.x - b.x, c.y - b.y);
+}
+
+/** Twice the signed area of a ring: positive counter-clockwise. */
+function signedArea2(ring: readonly Vec2[]): number {
+ let sum = 0;
+ for (let i = 0; i < ring.length; i++) {
+ const a = ring[i];
+ const b = ring[(i + 1) % ring.length];
+ sum += cross(a.x, a.y, b.x, b.y);
+ }
+ return sum;
+}
+
+/** No right turn anywhere. Collinear joints pass: Box2D merges those away itself. */
+function isConvex(ring: readonly Vec2[]): boolean {
+ for (let i = 0; i < ring.length; i++) {
+ const a = ring[(i + ring.length - 1) % ring.length];
+ const b = ring[i];
+ const c = ring[(i + 1) % ring.length];
+ if (turn(a, b, c) < 0) return false;
+ }
+ return true;
+}
+
+/**
+ * Whether two segments cross at a point interior to BOTH. Touching — an endpoint
+ * on a segment, two collinear runs — is not a crossing: a ring may legitimately
+ * fold back onto its own corner, and only a real crossing has no partition.
+ */
+function segmentsCross(a: Vec2, b: Vec2, c: Vec2, d: Vec2): boolean {
+ const d1 = cross(b.x - a.x, b.y - a.y, c.x - a.x, c.y - a.y);
+ const d2 = cross(b.x - a.x, b.y - a.y, d.x - a.x, d.y - a.y);
+ const d3 = cross(d.x - c.x, d.y - c.y, a.x - c.x, a.y - c.y);
+ const d4 = cross(d.x - c.x, d.y - c.y, b.x - c.x, b.y - c.y);
+ return d1 !== 0 && d2 !== 0 && d3 !== 0 && d4 !== 0
+ && (d1 > 0) !== (d2 > 0) && (d3 > 0) !== (d4 > 0);
+}
+
+/**
+ * Whether any two non-adjacent edges cross. Asked outright rather than inferred
+ * from ear clipping running out of ears: a self-crossing ring often still yields
+ * ears, and the triangulation it yields covers the wrong area in silence.
+ */
+function selfIntersects(ring: readonly Vec2[]): boolean {
+ const n = ring.length;
+ for (let i = 0; i < n; i++) {
+ for (let j = i + 2; j < n; j++) {
+ if (i === 0 && j === n - 1) continue; // adjacent around the wrap
+ if (segmentsCross(ring[i], ring[(i + 1) % n], ring[j], ring[(j + 1) % n])) return true;
+ }
+ }
+ return false;
+}
+
+/** Strictly inside — a point ON an edge must not block the ear that owns it. */
+function inTriangle(p: Vec2, a: Vec2, b: Vec2, c: Vec2): boolean {
+ return cross(b.x - a.x, b.y - a.y, p.x - a.x, p.y - a.y) > 0
+ && cross(c.x - b.x, c.y - b.y, p.x - b.x, p.y - b.y) > 0
+ && cross(a.x - c.x, a.y - c.y, p.x - c.x, p.y - c.y) > 0;
+}
+
+/** The ring with consecutive duplicates removed, wound counter-clockwise. */
+function normalize(vertices: readonly Vec2[]): Vec2[] {
+ const out: Vec2[] = [];
+ for (const v of vertices) {
+ const last = out[out.length - 1];
+ if (last && Math.hypot(v.x - last.x, v.y - last.y) < WELD) continue;
+ out.push({ x: v.x, y: v.y });
+ }
+ const first = out[0];
+ const last = out[out.length - 1];
+ if (out.length > 1 && first && last && Math.hypot(first.x - last.x, first.y - last.y) < WELD) out.pop();
+ if (out.length >= MIN_POLYGON_VERTICES && signedArea2(out) < 0) out.reverse();
+ return out;
+}
+
+/**
+ * Triangles as index triples, or null when no ear can be found — which a simple
+ * ring always has, so failing means this one is not simple: it crosses itself,
+ * and no partition of it exists to compute.
+ */
+function earClip(pts: readonly Vec2[]): number[][] | null {
+ const live = pts.map((_, i) => i);
+ const out: number[][] = [];
+ while (live.length > 3) {
+ let clipped = -1;
+ for (let i = 0; i < live.length; i++) {
+ const a = live[(i + live.length - 1) % live.length];
+ const b = live[i];
+ const c = live[(i + 1) % live.length];
+ if (turn(pts[a], pts[b], pts[c]) <= 0) continue;
+ let blocked = false;
+ for (const k of live) {
+ if (k === a || k === b || k === c) continue;
+ if (inTriangle(pts[k], pts[a], pts[b], pts[c])) { blocked = true; break; }
+ }
+ if (blocked) continue;
+ out.push([a, b, c]);
+ clipped = i;
+ break;
+ }
+ if (clipped < 0) return null;
+ live.splice(clipped, 1);
+ }
+ out.push([live[0], live[1], live[2]]);
+ return out;
+}
+
+/** Two pieces joined along the edge they share, with that edge's own endpoints. */
+interface Join {
+ ring: number[];
+ u: number;
+ v: number;
+}
+
+/** The two pieces joined along the edge they share, or null when they share none. */
+function joined(a: readonly number[], b: readonly number[]): Join | null {
+ for (let i = 0; i < a.length; i++) {
+ const u = a[i];
+ const v = a[(i + 1) % a.length];
+ for (let j = 0; j < b.length; j++) {
+ // A consistently wound partition traverses a shared edge in opposite
+ // directions, which is what makes the walk below close.
+ if (b[j] !== v || b[(j + 1) % b.length] !== u) continue;
+ const ring: number[] = [];
+ for (let k = 0; k < a.length - 1; k++) ring.push(a[(i + 1 + k) % a.length]);
+ for (let k = 0; k < b.length - 1; k++) ring.push(b[(j + 1 + k) % b.length]);
+ return { ring, u, v };
+ }
+ }
+ return null;
+}
+
+/**
+ * Merge neighbours back while each result stays convex and within the cap,
+ * longest shared edge first. The candidate is tested for convexity outright
+ * rather than at the two joints the merge creates: on a polygon capped at eight
+ * vertices that walk is cheaper than being clever, and cannot mistake a winding.
+ */
+function mergePieces(pts: readonly Vec2[], pieces: number[][]): number[][] {
+ const key = (u: number, v: number): number => u * pts.length + v;
+ for (;;) {
+ // Who owns each directed edge, so candidates come from adjacency rather
+ // than from every pair: a hundred-point ring starts as ninety-eight
+ // triangles, and all-pairs-every-round costs milliseconds.
+ const owner = new Map<number, number>();
+ for (let i = 0; i < pieces.length; i++) {
+ const ring = pieces[i];
+ for (let k = 0; k < ring.length; k++) owner.set(key(ring[k], ring[(k + 1) % ring.length]), i);
+ }
+
+ let best = -1;
+ let bestA = -1;
+ let bestB = -1;
+ let bestRing: number[] | null = null;
+ for (let i = 0; i < pieces.length; i++) {
+ const ring = pieces[i];
+ for (let k = 0; k < ring.length; k++) {
+ const j = owner.get(key(ring[(k + 1) % ring.length], ring[k]));
+ // `j > i` takes each neighbouring pair once: the shared edge is
+ // reachable from both of its sides.
+ if (j === undefined || j <= i) continue;
+ if (ring.length + pieces[j].length - 2 > MAX_POLYGON_VERTICES) continue;
+ const join = joined(ring, pieces[j]);
+ if (!join || !isConvex(join.ring.map((n) => pts[n]))) continue;
+ // What the merge buys: the shared edge stops being a wall between
+ // two shapes. The longest one is the most wall removed.
+ const u = pts[join.u];
+ const v = pts[join.v];
+ const value = (u.x - v.x) ** 2 + (u.y - v.y) ** 2;
+ if (value <= best) continue;
+ best = value;
+ bestA = i;
+ bestB = j;
+ bestRing = join.ring;
+ }
+ }
+ if (!bestRing) return pieces;
+ pieces.splice(bestB, 1);
+ pieces[bestA] = bestRing;
+ }
+}
+
+/** What a collider ring collides as, once Box2D's two constraints are applied.
+ * Shared with every caller that asks about the same ring, so treat it as frozen. */
+export interface PolygonDecomposition {
+ /** Convex pieces, each counter-clockwise and within the solver's vertex cap. */
+ readonly pieces: readonly Vec2[][];
+ /** The ring crosses itself, so no partition of it exists: `pieces` is the
+ * convex hull, which is what the solver falls back to. */
+ degenerate: boolean;
+}
+
+/**
+ * One answer per vertex array: the gizmo asks about the same ring every frame,
+ * and a hundred-vertex one measures milliseconds to partition. The key is the
+ * ARRAY, so an edit writes a new one and misses — while a mutation in place hits
+ * a stale entry, as does the solver, whose shapes that same flag rebuilds.
+ */
+const memo = new WeakMap<object, PolygonDecomposition>();
+
+/**
+ * The convex pieces `vertices` collides as. A ring already convex and within the
+ * cap is ONE piece and the same points, so the common shape costs nothing and
+ * keeps the identity an author drew.
+ */
+export function decomposePolygon2D(vertices: readonly Vec2[]): PolygonDecomposition {
+ const hit = memo.get(vertices);
+ if (hit) return hit;
+ const out = partition(vertices);
+ memo.set(vertices, out);
+ return out;
+}
+
+function partition(vertices: readonly Vec2[]): PolygonDecomposition {
+ const ring = normalize(vertices);
+ if (ring.length < MIN_POLYGON_VERTICES) return { pieces: [], degenerate: false };
+
+ // The hull is the solver's own verdict on whether these points are a shape at
+ // all — welded down to a line, or to fewer than three. Asking it here keeps
+ // the fast path below from handing back a ring Box2D would refuse.
+ const hull = computePolygonHull(ring);
+ if (hull.length < MIN_POLYGON_VERTICES) return { pieces: [], degenerate: false };
+
+ if (selfIntersects(ring)) return { pieces: [hull], degenerate: true };
+ if (ring.length <= MAX_POLYGON_VERTICES && isConvex(ring)) {
+ return { pieces: [ring], degenerate: false };
+ }
+
+ const triangles = earClip(ring);
+ if (!triangles) return { pieces: [hull], degenerate: true };
+
+ // Each piece is finally what Box2D would make of it, so a sliver the solver
+ // refuses is dropped where it can be seen rather than at shape creation.
+ const pieces = mergePieces(ring, triangles)
+ .map((indices) => computePolygonHull(indices.map((k) => ring[k])))
+ .filter((piece) => piece.length >= MIN_POLYGON_VERTICES);
+ return { pieces, degenerate: false };
+}
diff --git a/sdk/src/physics/polygonHull2D.ts b/sdk/src/physics/polygonHull2D.ts
index 4a8ada35f..317abdcfe 100644
--- a/sdk/src/physics/polygonHull2D.ts
+++ b/sdk/src/physics/polygonHull2D.ts
@@ -2,18 +2,17 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file polygonHull2D.ts
- * @brief The polygon Box2D actually builds from a PolygonCollider2D's vertices.
+ * @brief The polygon Box2D actually builds from one set of points.
*
- * @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.
+ * @details Handing `b2CreatePolygonShape` a ring is not handing it that ring: it
+ * takes the CONVEX HULL, welding points within slop, dropping ones its
+ * neighbours already span, and refusing the lot when fewer than three
+ * survive. A caller that does not know this draws shapes nobody can hit.
*
- * 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.
+ * A port of `b2ComputeHull` (third_party/box2d/src/hull.c), kept faithful
+ * to its welding and collinear slop because its whole job is AGREEMENT.
+ * Concavity is answered a level up, in {@link decomposePolygon2D}, which
+ * uses this to know what the solver will make of each piece it proposes.
*
* Units are physics metres — the slop below is metres, so a hull
* computed in pixels would weld at a thousand times the real tolerance.
@@ -21,9 +20,9 @@
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.
+ * The most vertices Box2D stores in ONE polygon (`B2_MAX_POLYGON_VERTICES`). It
+ * caps a convex piece, not what an author may draw: a ring past it is divided
+ * into pieces that each fit.
*/
export const MAX_POLYGON_VERTICES = 8;
@@ -138,30 +137,3 @@ function mergeCollinear(hull: Vec2[]): Vec2[] {
}
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/concave-collider-smoke.mjs b/sdk/tests/concave-collider-smoke.mjs
new file mode 100644
index 000000000..070efc321
--- /dev/null
+++ b/sdk/tests/concave-collider-smoke.mjs
@@ -0,0 +1,94 @@
+/**
+ * A concave PolygonCollider2D against the real Box2D. The shape is a cup, whose
+ * convex hull is a filled rectangle: a body dropped in rests on the floor at
+ * y≈0.2, and on a sealed lid at y≈3.2 if anything stops dividing it. Both are
+ * asserted, because the second is what makes the first mean anything.
+ */
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { requireWasm } from '../../tools/lib/wasmDir.mjs';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const { decomposePolygon2D, computePolygonHull } =
+ await import('file://' + path.join(HERE, '..', 'dist', 'physics', 'index.js').replace(/\\/g, '/'));
+
+const wasmDir = requireWasm('physics.wasm');
+const factory = (await import('file://' + path.join(wasmDir, 'physics.js').replace(/\\/g, '/'))).default;
+const m = await factory({ wasmBinary: readFileSync(path.join(wasmDir, 'physics.wasm')) });
+
+let pass = true;
+const check = (name, cond, detail) => {
+ console.log(`${cond ? 'PASS' : 'FAIL'} ${name} ${detail ?? ''}`);
+ if (!cond) pass = false;
+};
+
+const STATIC = 0, DYNAMIC = 2;
+const CUP = 1, DROP = 2;
+
+function bodyPos(entity) {
+ const count = m._physics_getDynamicBodyCount();
+ const base = m._physics_getDynamicBodyTransforms() >> 2;
+ for (let i = 0; i < count; i++) {
+ const o = base + i * 4;
+ if (m.HEAPU32[o] === entity) return { x: m.HEAPF32[o + 1], y: m.HEAPF32[o + 2] };
+ }
+ return null;
+}
+
+/** One convex piece as a Box2D polygon shape on `entity`'s body. */
+function addPiece(entity, piece) {
+ const ptr = m._malloc(piece.length * 2 * 4);
+ const base = ptr >> 2;
+ for (let i = 0; i < piece.length; i++) {
+ m.HEAPF32[base + i * 2] = piece[i].x;
+ m.HEAPF32[base + i * 2 + 1] = piece[i].y;
+ }
+ m._physics_addPolygonShape(entity, ptr, piece.length, 0, 1, 0.3, 0, 0, 1, 0xffff);
+ m._free(ptr);
+}
+
+// A cup: a floor at y=0 between x=±1, two walls up to y=3, and a solid base under
+// it. The mouth is open; the hull closes it.
+const CUP_RING = [
+ { x: -2, y: -1 }, { x: 2, y: -1 }, { x: 2, y: 3 }, { x: 1, y: 3 },
+ { x: 1, y: 0 }, { x: -1, y: 0 }, { x: -1, y: 3 }, { x: -2, y: 3 },
+];
+
+/** Drop a small box down the middle from `y`, and answer where it stops. */
+function dropInto(pieces, fromY) {
+ m._physics_init(0, -9.81, 1 / 60, 4, 30, 10, 3);
+ m._physics_createBody(CUP, STATIC, 0, 0, 0, 1, 0, 0, 0, 0);
+ for (const piece of pieces) addPiece(CUP, piece);
+ m._physics_createBody(DROP, DYNAMIC, 0, fromY, 0, 1, 0, 0, 0, 0);
+ m._physics_addBoxShape(DROP, 0.2, 0.2, 0, 0, 0, 1, 0.3, 0, 0, 1, 0xffff);
+ for (let i = 0; i < 420; i++) m._physics_step(1 / 60);
+ const at = bodyPos(DROP);
+ m._physics_shutdown();
+ return at;
+}
+
+const { pieces, degenerate } = decomposePolygon2D(CUP_RING);
+check('the cup partitions', !degenerate && pieces.length > 1, `${pieces.length} piece(s)`);
+check('every piece fits one Box2D polygon', pieces.every((p) => p.length >= 3 && p.length <= 8),
+ pieces.map((p) => p.length).join('+'));
+
+// The claim: the mouth is open, so the box reaches the floor at y=0 and rests at
+// its own half-height above it.
+const landed = dropInto(pieces, 5);
+check('a body falls INTO the concave cup', landed && Math.abs(landed.y - 0.2) < 0.1,
+ `y=${landed?.y.toFixed(3)} (want ≈0.2, the floor)`);
+check('and it stayed down the middle rather than sliding out', landed && Math.abs(landed.x) < 0.8,
+ `x=${landed?.x.toFixed(3)}`);
+
+// The control. Against the same ring's hull the mouth is sealed and the same drop
+// rests on the rim — so the assertion above is measuring the decomposition, not
+// merely that something stopped the box.
+const onLid = dropInto([computePolygonHull(CUP_RING)], 5);
+check('the hull of the same ring seals it — the control', onLid && Math.abs(onLid.y - 3.2) < 0.1,
+ `y=${onLid?.y.toFixed(3)} (want ≈3.2, the sealed rim)`);
+check('the two answers are far apart', landed && onLid && onLid.y - landed.y > 2.5,
+ `${landed?.y.toFixed(3)} vs ${onLid?.y.toFixed(3)}`);
+
+console.log(pass ? '\nconcave-collider-smoke: PASS' : '\nconcave-collider-smoke: FAIL');
+process.exit(pass ? 0 : 1);
diff --git a/sdk/tests/polygon-decompose.test.ts b/sdk/tests/polygon-decompose.test.ts
new file mode 100644
index 000000000..335d7c79a
--- /dev/null
+++ b/sdk/tests/polygon-decompose.test.ts
@@ -0,0 +1,188 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file polygon-decompose.test.ts — a concave ring as the shapes it collides as.
+ *
+ * The properties matter more than the piece count: any partition is correct if
+ * every piece is convex, within the solver's cap, and the pieces together cover
+ * the ring and nothing outside it. Asserting a count would pin the algorithm
+ * rather than the contract, so only the cases with one obvious answer do.
+ *
+ * Coverage is checked by sampling: points known to be inside the ring must land
+ * in some piece, and points in a notch must land in none. That is the property a
+ * player actually feels — whether they can walk into the dent.
+ */
+import { describe, it, expect } from 'vitest';
+import { decomposePolygon2D } from '../src/physics/polygonDecompose2D';
+import { MAX_POLYGON_VERTICES, MIN_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 cross = (ax: number, ay: number, bx: number, by: number) => ax * by - ay * bx;
+
+/** Inside or on the boundary of a convex CCW ring. */
+function inPiece(q: P, ring: readonly P[]): boolean {
+ for (let i = 0; i < ring.length; i++) {
+ const a = ring[i];
+ const b = ring[(i + 1) % ring.length];
+ if (cross(b.x - a.x, b.y - a.y, q.x - a.x, q.y - a.y) < -1e-9) return false;
+ }
+ return true;
+}
+
+const covered = (q: P, pieces: readonly P[][]) => pieces.some((piece) => inPiece(q, piece));
+
+/** Every piece a shape Box2D will take: convex, wound CCW, within the cap. */
+function expectWellFormed(pieces: readonly P[][]) {
+ expect(pieces.length).toBeGreaterThan(0);
+ for (const ring of pieces) {
+ expect(ring.length).toBeGreaterThanOrEqual(MIN_POLYGON_VERTICES);
+ expect(ring.length).toBeLessThanOrEqual(MAX_POLYGON_VERTICES);
+ let area2 = 0;
+ for (let i = 0; i < ring.length; i++) {
+ const a = ring[i];
+ const b = ring[(i + 1) % ring.length];
+ area2 += cross(a.x, a.y, b.x, b.y);
+ const c = ring[(i + 2) % ring.length];
+ expect(cross(b.x - a.x, b.y - a.y, c.x - b.x, c.y - b.y)).toBeGreaterThanOrEqual(-1e-9);
+ }
+ expect(area2).toBeGreaterThan(0); // counter-clockwise, with real area
+ }
+}
+
+// A dart: three corners with the bottom edge pushed up into the middle.
+const DART = [p(-1, -1), p(0, 0), p(1, -1), p(0, 1)];
+// An L, the textbook concave case: one inner corner.
+const L = [p(0, 0), p(2, 0), p(2, 1), p(1, 1), p(1, 2), p(0, 2)];
+// A C, which no single split can solve — the mouth is deep.
+const C = [
+ p(0, 0), p(3, 0), p(3, 1), p(1, 1), p(1, 2), p(3, 2), p(3, 3), p(0, 3),
+];
+
+describe('decomposePolygon2D', () => {
+ it('leaves a convex ring alone — one piece, the points as drawn', () => {
+ const square = [p(-1, -1), p(1, -1), p(1, 1), p(-1, 1)];
+ const d = decomposePolygon2D(square);
+ expect(d.degenerate).toBe(false);
+ expect(d.pieces).toHaveLength(1);
+ expect(d.pieces[0]).toEqual(square);
+ });
+
+ it('rewinds a clockwise ring rather than refusing it', () => {
+ const cw = [p(-1, -1), p(-1, 1), p(1, 1), p(1, -1)];
+ const d = decomposePolygon2D(cw);
+ expect(d.pieces).toHaveLength(1);
+ expectWellFormed(d.pieces);
+ });
+
+ it('splits a dart, and the notch is no longer solid', () => {
+ const d = decomposePolygon2D(DART);
+ expect(d.degenerate).toBe(false);
+ expectWellFormed(d.pieces);
+ expect(d.pieces.length).toBeGreaterThan(1);
+ // Just below the notch vertex is outside the ring: the hull would cover it.
+ expect(covered(p(0, -0.5), d.pieces)).toBe(false);
+ // ...while the two lobes beside it are still solid.
+ expect(covered(p(-0.5, -0.3), d.pieces)).toBe(true);
+ expect(covered(p(0.5, -0.3), d.pieces)).toBe(true);
+ expect(covered(p(0, 0.5), d.pieces)).toBe(true);
+ });
+
+ it('splits an L and leaves the missing quadrant empty', () => {
+ const d = decomposePolygon2D(L);
+ expectWellFormed(d.pieces);
+ expect(covered(p(0.5, 0.5), d.pieces)).toBe(true);
+ expect(covered(p(1.5, 0.5), d.pieces)).toBe(true);
+ expect(covered(p(0.5, 1.5), d.pieces)).toBe(true);
+ expect(covered(p(1.5, 1.5), d.pieces)).toBe(false); // the quadrant the L omits
+ });
+
+ it('keeps the mouth of a C open', () => {
+ const d = decomposePolygon2D(C);
+ expectWellFormed(d.pieces);
+ expect(covered(p(2, 1.5), d.pieces)).toBe(false); // inside the mouth
+ expect(covered(p(0.5, 1.5), d.pieces)).toBe(true); // the spine behind it
+ expect(covered(p(2, 0.5), d.pieces)).toBe(true); // the lower arm
+ expect(covered(p(2, 2.5), d.pieces)).toBe(true); // the upper arm
+ });
+
+ it('takes a ring far past the solver cap, in pieces that each obey it', () => {
+ // A 24-point star: twelve reflex vertices, nothing a single polygon can hold.
+ const star: P[] = [];
+ for (let i = 0; i < 24; i++) {
+ const a = (i * 2 * Math.PI) / 24;
+ const r = i % 2 === 0 ? 2 : 1;
+ star.push(p(r * Math.cos(a), r * Math.sin(a)));
+ }
+ const d = decomposePolygon2D(star);
+ expect(d.degenerate).toBe(false);
+ expectWellFormed(d.pieces);
+ expect(covered(p(0, 0), d.pieces)).toBe(true); // the body
+ expect(covered(p(1.9, 0), d.pieces)).toBe(true); // out along a spike
+ expect(covered(p(1.35, 1.35), d.pieces)).toBe(false); // the gap between two
+ });
+
+ it('is deterministic — the same ring gives the same pieces every time', () => {
+ expect(decomposePolygon2D(C).pieces).toEqual(decomposePolygon2D(C).pieces);
+ });
+
+ it('falls back to the hull for a ring that crosses itself, and says so', () => {
+ const bowtie = [p(-1, -1), p(1, 1), p(1, -1), p(-1, 1)];
+ const d = decomposePolygon2D(bowtie);
+ expect(d.degenerate).toBe(true);
+ expectWellFormed(d.pieces);
+ expect(d.pieces).toHaveLength(1);
+ });
+
+ it('builds nothing from a ring with no shape in it', () => {
+ expect(decomposePolygon2D([p(0, 0), p(1, 0)]).pieces).toEqual([]);
+ expect(decomposePolygon2D([]).pieces).toEqual([]);
+ // Three points on a line: welded and collinear, so the solver builds none.
+ expect(decomposePolygon2D([p(0, 0), p(1, 0), p(2, 0)]).pieces).toEqual([]);
+ });
+
+ it('welds a duplicated point rather than tripping over the zero-length edge', () => {
+ const d = decomposePolygon2D([p(0, 0), p(0.001, 0), p(2, 0), p(2, 1), p(1, 1), p(1, 2), p(0, 2)]);
+ expect(d.degenerate).toBe(false);
+ expectWellFormed(d.pieces);
+ expect(covered(p(1.5, 1.5), d.pieces)).toBe(false);
+ });
+});
+
+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, as authored', () => {
+ 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 ALSO draws once — the ring is what it collides as', () => {
+ const o = outlineOf(DART);
+ expect(o.declined).toBeUndefined();
+ expect(o.polylines).toHaveLength(1);
+ expect(o.polylines[0]).toHaveLength(5); // the authored 4, closed
+ });
+
+ it('a ring past the vertex cap draws whole, because it is built whole', () => {
+ const o = outlineOf(C);
+ expect(o.declined).toBeUndefined();
+ expect(o.polylines[0]).toHaveLength(C.length + 1);
+ });
+
+ it('a self-crossing ring draws its hull solid and the ring apart', () => {
+ const o = outlineOf([p(-1, -1), p(1, 1), p(1, -1), p(-1, 1)]);
+ expect(o.declined?.[0]).toHaveLength(5);
+ expect(o.polylines.length).toBeGreaterThan(0);
+ });
+
+ it('a ring with no area 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);
+ });
+});
diff --git a/sdk/tests/polygon-hull.test.ts b/sdk/tests/polygon-hull.test.ts
index 0b63d0314..3ba911811 100644
--- a/sdk/tests/polygon-hull.test.ts
+++ b/sdk/tests/polygon-hull.test.ts
@@ -13,12 +13,13 @@
* 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.
+ *
+ * Concavity is not this file's subject. A concave collider is divided into convex
+ * pieces before it reaches the solver — see polygon-decompose.test.ts; these are
+ * the rules each piece is then held to.
*/
import { describe, it, expect } from 'vitest';
-import {
- computePolygonHull, polygonHullDiff, MAX_POLYGON_VERTICES,
-} from '../src/physics/polygonHull2D';
-import { collider2DOutline, type Collider2DShape } from '../src/physics/ColliderShape2D';
+import { computePolygonHull, MAX_POLYGON_VERTICES } from '../src/physics/polygonHull2D';
type P = { x: number; y: number };
const p = (x: number, y: number): P => ({ x, y });
@@ -100,47 +101,5 @@ describe('computePolygonHull — measured against b2ComputeHull', () => {
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);
});
});
diff --git a/tools/check-physics2d.mjs b/tools/check-physics2d.mjs
index 04b5f7d9b..65dae440e 100644
--- a/tools/check-physics2d.mjs
+++ b/tools/check-physics2d.mjs
@@ -25,7 +25,8 @@ const TESTS = path.join(ROOT, 'sdk', 'tests');
const WASM = path.join(ROOT, 'build', 'wasm', 'web', 'physics.wasm');
/** The smokes this gate schedules, and the module each needs. */
-const SMOKES = ['mover-smoke.mjs', 'physics-features-smoke.mjs', 'sensor-smoke.mjs'];
+const SMOKES = ['mover-smoke.mjs', 'physics-features-smoke.mjs', 'sensor-smoke.mjs',
+ 'concave-collider-smoke.mjs'];
// Every smoke has to be scheduled by SOMEONE. Others run elsewhere (the 3D one
// is check-physics3d's), so a file is only orphaned when no gate names it.
@@ -68,4 +69,5 @@ for (const smoke of SMOKES) {
}
console.log(`check-physics2d: ${total} behaviour(s) hold across ${SMOKES.length} smoke(s)`
- + ' — mover rest/skin/snap/ceiling, joints and the mouse drag, sensor overlap.');
+ + ' — mover rest/skin/snap/ceiling, joints and the mouse drag, sensor overlap,'
+ + ' and a body falling into a concave collider rather than onto its hull.');