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.

refactor(physics): shared ColliderShape projection — one geometry seam for all visualizers

yhhb7912f8e6d6f
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index f6a7215d1..7132bb633 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: 1169 stable · 17 beta · 1 deprecated
+Symbols: 1177 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -1091,6 +1091,11 @@ scale: number | undefined
sprite: number | undefined
```
+## CAPSULE_ARC_SEGMENTS — const
+```
+16
+```
+
## CacheAsBitmap — const
```
ComponentDef<CacheAsBitmapData>
@@ -1363,6 +1368,28 @@ Depth = 2
Nothing = 0
```
+## ColliderInstance — interface
+```
+isSensor: boolean
+shape: ColliderShape
+```
+
+## ColliderOutline — interface
+```
+circles: { c: Vec2; r: number; }[]
+polylines: Vec2[][]
+```
+
+## ColliderShape — type
+```
+| { kind: 'box'; halfExtents: Vec2; offset: Vec2 }
+ | { kind: 'circle'; radius: number; offset: Vec2 }
+ | { kind: 'capsule'; radius: number; halfHeight: number; offset: Vec2 }
+ | { kind: 'segment'; point1: Vec2; point2: Vec2 }
+ | { kind: 'polygon'; vertices: Vec2[] }
+ | { kind: 'chain'; points: Vec2[]; isLoop: boolean }
+```
+
## CollisionEnterEvent — interface
```
contactX: number
@@ -7520,6 +7547,11 @@ BtPlugin
(asset: TilesetAsset): number[]
```
+## colliderShapeOutline — function
+```
+(shape: ColliderShape, center: Vec2, angle: number, ppu: number): ColliderOutline
+```
+
## color — const
```
(r?: number, g?: number, b?: number, a?: number) => Color
@@ -8560,6 +8592,11 @@ PrefabsPlugin
(radius: number, options?: RadiusInterestOptions): InterestPolicy
```
+## readColliderShapes — function
+```
+(world: World, entity: number): ColliderInstance[]
+```
+
## readPtrField — function
```
(f32: Float32Array, u32: Uint32Array, u8: Uint8Array, ptr: number, field: PtrFieldDesc): unknown
@@ -8915,6 +8952,16 @@ Plugin
(app: App, opts?: { amplitude?: number; rotation?: number; frequency?: number; duration?: number; }): void
```
+## shapeCenter — function
+```
+(shape: ColliderShape, worldPos: Vec2, angle: number, ppu: number): Vec2
+```
+
+## shapeOffset — function
+```
+(shape: ColliderShape): Vec2
+```
+
## shutdownDrawAPI — function
```
(): void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index cb415095e..8ce1a1ab6 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: 1168 stable · 19 beta · 1 deprecated
+Symbols: 1176 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -1086,6 +1086,11 @@ scale: number | undefined
sprite: number | undefined
```
+## CAPSULE_ARC_SEGMENTS — const
+```
+16
+```
+
## CacheAsBitmap — const
```
ComponentDef<CacheAsBitmapData>
@@ -1358,6 +1363,28 @@ Depth = 2
Nothing = 0
```
+## ColliderInstance — interface
+```
+isSensor: boolean
+shape: ColliderShape
+```
+
+## ColliderOutline — interface
+```
+circles: { c: Vec2; r: number; }[]
+polylines: Vec2[][]
+```
+
+## ColliderShape — type
+```
+| { kind: 'box'; halfExtents: Vec2; offset: Vec2 }
+ | { kind: 'circle'; radius: number; offset: Vec2 }
+ | { kind: 'capsule'; radius: number; halfHeight: number; offset: Vec2 }
+ | { kind: 'segment'; point1: Vec2; point2: Vec2 }
+ | { kind: 'polygon'; vertices: Vec2[] }
+ | { kind: 'chain'; points: Vec2[]; isLoop: boolean }
+```
+
## CollisionEnterEvent — interface
```
contactX: number
@@ -7515,6 +7542,11 @@ BtPlugin
(asset: TilesetAsset): number[]
```
+## colliderShapeOutline — function
+```
+(shape: ColliderShape, center: Vec2, angle: number, ppu: number): ColliderOutline
+```
+
## color — const
```
(r?: number, g?: number, b?: number, a?: number) => Color
@@ -8565,6 +8597,11 @@ PrefabsPlugin
(radius: number, options?: RadiusInterestOptions): InterestPolicy
```
+## readColliderShapes — function
+```
+(world: World, entity: number): ColliderInstance[]
+```
+
## readPtrField — function
```
(f32: Float32Array, u32: Uint32Array, u8: Uint8Array, ptr: number, field: PtrFieldDesc): unknown
@@ -8920,6 +8957,16 @@ Plugin
(app: App, opts?: { amplitude?: number; rotation?: number; frequency?: number; duration?: number; }): void
```
+## shapeCenter — function
+```
+(shape: ColliderShape, worldPos: Vec2, angle: number, ppu: number): Vec2
+```
+
+## shapeOffset — function
+```
+(shape: ColliderShape): Vec2
+```
+
## shutdownDrawAPI — function
```
(): void
diff --git a/sdk/etc/physics.api.md b/sdk/etc/physics.api.md
index 7fc1bacb3..dd448a521 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: 56 stable · 0 beta · 0 deprecated
+Symbols: 64 stable · 0 beta · 0 deprecated
## BodyType — enum
```
@@ -29,6 +29,11 @@ radius: number
restitution: number
```
+## CAPSULE_ARC_SEGMENTS — const
+```
+16
+```
+
## CapsuleCollider — const
```
BuiltinComponentDef<CapsuleColliderData>
@@ -104,6 +109,28 @@ radius: number
restitution: number
```
+## ColliderInstance — interface
+```
+isSensor: boolean
+shape: ColliderShape
+```
+
+## ColliderOutline — interface
+```
+circles: { c: Vec2; r: number; }[]
+polylines: Vec2[][]
+```
+
+## ColliderShape — type
+```
+| { kind: 'box'; halfExtents: Vec2; offset: Vec2 }
+ | { kind: 'circle'; radius: number; offset: Vec2 }
+ | { kind: 'capsule'; radius: number; halfHeight: number; offset: Vec2 }
+ | { kind: 'segment'; point1: Vec2; point2: Vec2 }
+ | { kind: 'polygon'; vertices: Vec2[] }
+ | { kind: 'chain'; points: Vec2[]; isLoop: boolean }
+```
+
## CollisionEnterEvent — interface
```
contactX: number
@@ -642,6 +669,11 @@ motorSpeed: number
upperTranslation: number
```
+## colliderShapeOutline — function
+```
+(shape: ColliderShape, center: Vec2, angle: number, ppu: number): ColliderOutline
+```
+
## drawPhysicsDebug — function
```
(app: App, physicsApiRes: ResourceDef<VelocityProvider>, physicsEventsRes: ResourceDef<PhysicsEventsData>): void
@@ -657,6 +689,11 @@ upperTranslation: number
(p: MoveAndSlideParams, cast: SlideCast): MoveAndSlideResult
```
+## readColliderShapes — function
+```
+(world: World, entity: number): ColliderInstance[]
+```
+
## registerCharacterControllerSystem — function
```
(app: App): void
@@ -667,3 +704,13 @@ upperTranslation: number
(app: App, physicsApiRes: ResourceDef<VelocityProvider>, physicsEventsRes: ResourceDef<PhysicsEventsData>): void
```
+## shapeCenter — function
+```
+(shape: ColliderShape, worldPos: Vec2, angle: number, ppu: number): Vec2
+```
+
+## shapeOffset — function
+```
+(shape: ColliderShape): Vec2
+```
+
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.ts
index 1af0b1fe0..7e7cb0031 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -158,6 +158,17 @@ export {
type CharacterControllerData,
} from './physics/CharacterController';
+export {
+ readColliderShapes,
+ shapeOffset,
+ shapeCenter,
+ colliderShapeOutline,
+ CAPSULE_ARC_SEGMENTS,
+ type ColliderShape,
+ type ColliderInstance,
+ type ColliderOutline,
+} from './physics/ColliderShape';
+
// =============================================================================
// Resources
// =============================================================================
diff --git a/sdk/src/physics/ColliderShape.ts b/sdk/src/physics/ColliderShape.ts
new file mode 100644
index 000000000..a1114fd52
--- /dev/null
+++ b/sdk/src/physics/ColliderShape.ts
@@ -0,0 +1,162 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ColliderShape.ts
+ * @brief The single geometry projection over the collider components — the shared
+ * seam for BOTH visualizers (the runtime PhysicsDebugDraw and the editor's
+ * collider gizmo) and for tile-collision overlays. It does NOT touch the
+ * runtime physics model: colliders stay ordinary C++/TS components dispatched
+ * by presence in PhysicsSystem; this only READS them into a shape descriptor,
+ * computes the offset+rotation center once (previously duplicated 3×), and
+ * emits world-space outlines each backend renders in its own primitives.
+ *
+ * Units: shape fields are physics metres (as stored on the components); `ppu`
+ * (pixels-per-unit) scales them to world pixels in shapeCenter / colliderShapeOutline.
+ */
+import type { Vec2 } from '../types';
+import type { World } from '../world';
+import {
+ BoxCollider, CircleCollider, CapsuleCollider,
+ SegmentCollider, PolygonCollider, ChainCollider,
+} from './PhysicsComponents';
+import type {
+ BoxColliderData, CircleColliderData, CapsuleColliderData,
+ SegmentColliderData, PolygonColliderData, ChainColliderData,
+} from './PhysicsComponents';
+
+/** Semicircle-cap segment count for a capsule outline (matches the legacy debug draw). */
+export const CAPSULE_ARC_SEGMENTS = 16;
+
+/** 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 ColliderShape =
+ | { kind: 'box'; halfExtents: Vec2; offset: Vec2 }
+ | { kind: 'circle'; radius: number; offset: Vec2 }
+ | { kind: 'capsule'; radius: number; halfHeight: number; offset: Vec2 }
+ | { kind: 'segment'; point1: Vec2; point2: Vec2 }
+ | { kind: 'polygon'; vertices: Vec2[] }
+ | { kind: 'chain'; points: Vec2[]; isLoop: boolean };
+
+/** A shape read off an entity, with the sensor flag the visualizers colour by. */
+export interface ColliderInstance {
+ shape: ColliderShape;
+ isSensor: boolean;
+}
+
+/** World-space (pixel) outline: straight runs as polylines + true circles left as
+ * {center, radius} so a backend can stroke them as arcs (SVG <circle> / circleOutline). */
+export interface ColliderOutline {
+ polylines: Vec2[][];
+ circles: { c: Vec2; r: number }[];
+}
+
+const ZERO: Vec2 = { x: 0, y: 0 };
+
+/** The collider's local offset in metres (0 for segment/polygon/chain, which have none). */
+export function shapeOffset(shape: ColliderShape): Vec2 {
+ return (shape.kind === 'box' || shape.kind === 'circle' || shape.kind === 'capsule')
+ ? shape.offset
+ : ZERO;
+}
+
+/**
+ * The shape's world-pixel centre = the entity's world position plus its collider offset
+ * (metres × ppu) rotated by the entity angle. This is the offset+rotation transform that
+ * used to be re-implemented in PhysicsDebugDraw and ViewportController.
+ */
+export function shapeCenter(shape: ColliderShape, worldPos: Vec2, angle: number, ppu: number): Vec2 {
+ const off = shapeOffset(shape);
+ const ox = off.x * ppu;
+ const oy = off.y * ppu;
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ return { x: worldPos.x + ox * cos - oy * sin, y: worldPos.y + ox * sin + oy * cos };
+}
+
+/**
+ * The shape's outline in world pixels, rotated by `angle` about `center` (see
+ * {@link shapeCenter}). Straight-edged shapes return closed/open polylines; a circle
+ * returns a single {c, r} for the backend to stroke as an arc.
+ */
+export function colliderShapeOutline(shape: ColliderShape, center: Vec2, angle: number, ppu: number): ColliderOutline {
+ const cos = Math.cos(angle);
+ const sin = Math.sin(angle);
+ // local (px) → world (px), rotated about center.
+ const w = (lx: number, ly: number): Vec2 => ({ x: center.x + lx * cos - ly * sin, y: center.y + lx * sin + ly * cos });
+
+ switch (shape.kind) {
+ case 'box': {
+ const hx = shape.halfExtents.x * ppu;
+ const hy = shape.halfExtents.y * ppu;
+ const p = [w(-hx, -hy), w(hx, -hy), w(hx, hy), w(-hx, hy)];
+ return { polylines: [[...p, p[0]]], circles: [] };
+ }
+ case 'circle':
+ return { polylines: [], circles: [{ c: center, r: shape.radius * ppu }] };
+ case 'capsule': {
+ const r = shape.radius * ppu;
+ const hh = shape.halfHeight * ppu;
+ // One closed loop tracing: left side ↑, top cap arc →, right side ↓, bottom cap
+ // arc ← — the exact same segment set the legacy drawCapsule emitted.
+ const pts: Vec2[] = [w(-r, -hh), w(-r, hh)];
+ for (let i = 1; i <= CAPSULE_ARC_SEGMENTS; i++) {
+ const a = (i / CAPSULE_ARC_SEGMENTS) * Math.PI;
+ pts.push(w(-r * Math.cos(a), hh + r * Math.sin(a)));
+ }
+ pts.push(w(r, -hh));
+ for (let i = 1; i <= CAPSULE_ARC_SEGMENTS; i++) {
+ const a = Math.PI + (i / CAPSULE_ARC_SEGMENTS) * Math.PI;
+ pts.push(w(-r * Math.cos(a), -hh + r * Math.sin(a)));
+ }
+ return { polylines: [pts], circles: [] };
+ }
+ case 'segment':
+ return {
+ polylines: [[w(shape.point1.x * ppu, shape.point1.y * ppu), w(shape.point2.x * ppu, shape.point2.y * ppu)]],
+ 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: [] };
+ }
+ case 'chain': {
+ const p = shape.points.map((v) => w(v.x * ppu, v.y * ppu));
+ if (p.length < 2) return { polylines: [], circles: [] };
+ return { polylines: [shape.isLoop ? [...p, p[0]] : p], circles: [] };
+ }
+ }
+}
+
+/**
+ * Read every collider component present on `entity` into shape descriptors, in the same
+ * order PhysicsSystem's addShapeForEntity dispatches (box, circle, capsule, segment,
+ * polygon, chain). Chain has no sensor flag, so it reports isSensor: false.
+ */
+export function readColliderShapes(world: World, entity: number): ColliderInstance[] {
+ const out: ColliderInstance[] = [];
+ if (world.has(entity, BoxCollider)) {
+ const b = world.get(entity, BoxCollider) as BoxColliderData;
+ out.push({ shape: { kind: 'box', halfExtents: b.halfExtents, offset: b.offset }, isSensor: b.isSensor });
+ }
+ if (world.has(entity, CircleCollider)) {
+ const c = world.get(entity, CircleCollider) as CircleColliderData;
+ out.push({ shape: { kind: 'circle', radius: c.radius, offset: c.offset }, isSensor: c.isSensor });
+ }
+ if (world.has(entity, CapsuleCollider)) {
+ const c = world.get(entity, CapsuleCollider) as CapsuleColliderData;
+ out.push({ shape: { kind: 'capsule', radius: c.radius, halfHeight: c.halfHeight, offset: c.offset }, isSensor: c.isSensor });
+ }
+ if (world.has(entity, SegmentCollider)) {
+ const s = world.get(entity, SegmentCollider) as SegmentColliderData;
+ out.push({ shape: { kind: 'segment', point1: s.point1, point2: s.point2 }, isSensor: s.isSensor });
+ }
+ if (world.has(entity, PolygonCollider)) {
+ const p = world.get(entity, PolygonCollider) as PolygonColliderData;
+ out.push({ shape: { kind: 'polygon', vertices: p.vertices }, isSensor: p.isSensor });
+ }
+ if (world.has(entity, ChainCollider)) {
+ const c = world.get(entity, ChainCollider) as ChainColliderData;
+ out.push({ shape: { kind: 'chain', points: c.points, isLoop: c.isLoop }, isSensor: false });
+ }
+ return out;
+}
diff --git a/sdk/src/physics/PhysicsDebugDraw.ts b/sdk/src/physics/PhysicsDebugDraw.ts
index 5262a7875..76f16637b 100644
--- a/sdk/src/physics/PhysicsDebugDraw.ts
+++ b/sdk/src/physics/PhysicsDebugDraw.ts
@@ -4,19 +4,14 @@ import type { App } from '../app';
import type { Color } from '../types';
import type { TransformData, CanvasData } from '../component';
import type { ResourceDef } from '../resource';
-import type {
- RigidBodyData, BoxColliderData, CircleColliderData, CapsuleColliderData,
- SegmentColliderData, PolygonColliderData, ChainColliderData,
-} from './PhysicsComponents';
+import type { RigidBodyData } from './PhysicsComponents';
import type { PhysicsEventsData } from './PhysicsPlugin';
import { Transform, Canvas } from '../component';
import { Draw } from '../draw';
import { defineResource } from '../resource';
import { registerDrawCallback } from '../customDraw';
-import {
- RigidBody, BoxCollider, CircleCollider, CapsuleCollider,
- SegmentCollider, PolygonCollider, ChainCollider, BodyType,
-} from './PhysicsComponents';
+import { RigidBody, BodyType } from './PhysicsComponents';
+import { readColliderShapes, shapeCenter, colliderShapeOutline } from './ColliderShape';
export interface PhysicsDebugDrawConfig {
enabled: boolean;
@@ -46,7 +41,6 @@ const DEBUG_LINE_THICKNESS = 1.5;
const CONTACT_POINT_RADIUS = 3;
const VELOCITY_SCALE = 0.5;
const CIRCLE_SEGMENTS = 32;
-const CAPSULE_ARC_SEGMENTS = 16;
function quatToAngleZ(q: { w: number; x: number; y: number; z: number }): number {
return Math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z));
@@ -72,78 +66,6 @@ function readPixelsPerUnit(app: App): number {
return 100;
}
-function drawRotatedBox(
- cx: number, cy: number,
- halfW: number, halfH: number,
- angle: number, color: Color,
-): void {
- const cos = Math.cos(angle);
- const sin = Math.sin(angle);
- const corners = [
- { x: -halfW, y: -halfH },
- { x: halfW, y: -halfH },
- { x: halfW, y: halfH },
- { x: -halfW, y: halfH },
- ];
- const pts = corners.map(c => ({
- x: cx + c.x * cos - c.y * sin,
- y: cy + c.x * sin + c.y * cos,
- }));
- for (let i = 0; i < 4; i++) {
- Draw.line(pts[i], pts[(i + 1) % 4], color, DEBUG_LINE_THICKNESS);
- }
-}
-
-function drawCapsule(
- cx: number, cy: number,
- radius: number, halfHeight: number,
- angle: number, color: Color,
-): void {
- const cos = Math.cos(angle);
- const sin = Math.sin(angle);
-
- const toWorld = (lx: number, ly: number) => ({
- x: cx + lx * cos - ly * sin,
- y: cy + lx * sin + ly * cos,
- });
-
- const topLeft = toWorld(-radius, halfHeight);
- const topRight = toWorld(radius, halfHeight);
- const bottomLeft = toWorld(-radius, -halfHeight);
- const bottomRight = toWorld(radius, -halfHeight);
-
- Draw.line(topLeft, bottomLeft, color, DEBUG_LINE_THICKNESS);
- Draw.line(topRight, bottomRight, color, DEBUG_LINE_THICKNESS);
-
- for (let i = 0; i < CAPSULE_ARC_SEGMENTS; i++) {
- const a0 = (i / CAPSULE_ARC_SEGMENTS) * Math.PI;
- const a1 = ((i + 1) / CAPSULE_ARC_SEGMENTS) * Math.PI;
- const p0 = toWorld(
- -radius * Math.cos(a0),
- halfHeight + radius * Math.sin(a0),
- );
- const p1 = toWorld(
- -radius * Math.cos(a1),
- halfHeight + radius * Math.sin(a1),
- );
- Draw.line(p0, p1, color, DEBUG_LINE_THICKNESS);
- }
-
- for (let i = 0; i < CAPSULE_ARC_SEGMENTS; i++) {
- const a0 = Math.PI + (i / CAPSULE_ARC_SEGMENTS) * Math.PI;
- const a1 = Math.PI + ((i + 1) / CAPSULE_ARC_SEGMENTS) * Math.PI;
- const p0 = toWorld(
- -radius * Math.cos(a0),
- -halfHeight + radius * Math.sin(a0),
- );
- const p1 = toWorld(
- -radius * Math.cos(a1),
- -halfHeight + radius * Math.sin(a1),
- );
- Draw.line(p0, p1, color, DEBUG_LINE_THICKNESS);
- }
-}
-
function drawVelocityArrow(
x: number, y: number,
vx: number, vy: number,
@@ -195,92 +117,20 @@ export function drawPhysicsDebug(
const angle = quatToAngleZ(wt.worldRotation);
if (config.showColliders) {
- if (app.world.has(entity, BoxCollider)) {
- const box = app.world.get(entity, BoxCollider) as BoxColliderData;
- const baseColor = box.isSensor ? SENSOR_COLOR : bodyTypeColor(rb.bodyType);
- const offsetX = box.offset.x * ppu;
- const offsetY = box.offset.y * ppu;
- const cosA = Math.cos(angle);
- const sinA = Math.sin(angle);
- const cx = wx + offsetX * cosA - offsetY * sinA;
- const cy = wy + offsetX * sinA + offsetY * cosA;
- drawRotatedBox(cx, cy, box.halfExtents.x * ppu, box.halfExtents.y * ppu, angle, baseColor);
- }
-
- if (app.world.has(entity, CircleCollider)) {
- const circle = app.world.get(entity, CircleCollider) as CircleColliderData;
- const baseColor = circle.isSensor ? SENSOR_COLOR : bodyTypeColor(rb.bodyType);
- const offsetX = circle.offset.x * ppu;
- const offsetY = circle.offset.y * ppu;
- const cosA = Math.cos(angle);
- const sinA = Math.sin(angle);
- const cx = wx + offsetX * cosA - offsetY * sinA;
- const cy = wy + offsetX * sinA + offsetY * cosA;
- Draw.circleOutline(
- { x: cx, y: cy },
- circle.radius * ppu,
- baseColor,
- DEBUG_LINE_THICKNESS,
- CIRCLE_SEGMENTS,
- );
- }
-
- if (app.world.has(entity, CapsuleCollider)) {
- const capsule = app.world.get(entity, CapsuleCollider) as CapsuleColliderData;
- const baseColor = capsule.isSensor ? SENSOR_COLOR : bodyTypeColor(rb.bodyType);
- const offsetX = capsule.offset.x * ppu;
- const offsetY = capsule.offset.y * ppu;
- const cosA = Math.cos(angle);
- const sinA = Math.sin(angle);
- const cx = wx + offsetX * cosA - offsetY * sinA;
- const cy = wy + offsetX * sinA + offsetY * cosA;
- drawCapsule(cx, cy, capsule.radius * ppu, capsule.halfHeight * ppu, angle, baseColor);
- }
-
- if (app.world.has(entity, SegmentCollider)) {
- const seg = app.world.get(entity, SegmentCollider) as SegmentColliderData;
- const baseColor = seg.isSensor ? SENSOR_COLOR : bodyTypeColor(rb.bodyType);
- const cosA = Math.cos(angle);
- const sinA = Math.sin(angle);
- const p1x = wx + (seg.point1.x * ppu * cosA - seg.point1.y * ppu * sinA);
- const p1y = wy + (seg.point1.x * ppu * sinA + seg.point1.y * ppu * cosA);
- const p2x = wx + (seg.point2.x * ppu * cosA - seg.point2.y * ppu * sinA);
- const p2y = wy + (seg.point2.x * ppu * sinA + seg.point2.y * ppu * cosA);
- Draw.line({ x: p1x, y: p1y }, { x: p2x, y: p2y }, baseColor, DEBUG_LINE_THICKNESS);
- }
-
- if (app.world.has(entity, PolygonCollider)) {
- const poly = app.world.get(entity, PolygonCollider) as PolygonColliderData;
- const baseColor = poly.isSensor ? SENSOR_COLOR : bodyTypeColor(rb.bodyType);
- const cosA = Math.cos(angle);
- const sinA = Math.sin(angle);
- const verts = poly.vertices;
- for (let vi = 0; vi < verts.length; vi++) {
- const v0 = verts[vi];
- const v1 = verts[(vi + 1) % verts.length];
- const x0 = wx + (v0.x * ppu * cosA - v0.y * ppu * sinA);
- const y0 = wy + (v0.x * ppu * sinA + v0.y * ppu * cosA);
- const x1 = wx + (v1.x * ppu * cosA - v1.y * ppu * sinA);
- const y1 = wy + (v1.x * ppu * sinA + v1.y * ppu * cosA);
- Draw.line({ x: x0, y: y0 }, { x: x1, y: y1 }, baseColor, DEBUG_LINE_THICKNESS);
+ // One projection for every shape: read the collider(s), take the offset+rotation
+ // centre, and stroke the world-space outline. Same geometry the per-type branches
+ // produced, now shared with the editor gizmo (see ColliderShape).
+ for (const { shape, isSensor } of readColliderShapes(app.world, entity)) {
+ const color = isSensor ? SENSOR_COLOR : bodyTypeColor(rb.bodyType);
+ const center = shapeCenter(shape, { x: wx, y: wy }, angle, ppu);
+ const outline = colliderShapeOutline(shape, center, angle, ppu);
+ for (const pl of outline.polylines) {
+ for (let i = 0; i + 1 < pl.length; i++) {
+ Draw.line(pl[i], pl[i + 1], color, DEBUG_LINE_THICKNESS);
+ }
}
- }
-
- if (app.world.has(entity, ChainCollider)) {
- const chain = app.world.get(entity, ChainCollider) as ChainColliderData;
- const baseColor = bodyTypeColor(rb.bodyType);
- const cosA = Math.cos(angle);
- const sinA = Math.sin(angle);
- const pts = chain.points;
- const end = chain.isLoop ? pts.length : pts.length - 1;
- for (let pi = 0; pi < end; pi++) {
- const p0 = pts[pi];
- const p1 = pts[(pi + 1) % pts.length];
- const x0 = wx + (p0.x * ppu * cosA - p0.y * ppu * sinA);
- const y0 = wy + (p0.x * ppu * sinA + p0.y * ppu * cosA);
- const x1 = wx + (p1.x * ppu * cosA - p1.y * ppu * sinA);
- const y1 = wy + (p1.x * ppu * sinA + p1.y * ppu * cosA);
- Draw.line({ x: x0, y: y0 }, { x: x1, y: y1 }, baseColor, DEBUG_LINE_THICKNESS);
+ for (const circ of outline.circles) {
+ Draw.circleOutline(circ.c, circ.r, color, DEBUG_LINE_THICKNESS, CIRCLE_SEGMENTS);
}
}
}
diff --git a/sdk/src/physics/index.ts b/sdk/src/physics/index.ts
index 4fdc0b9fd..4a8b6541a 100644
--- a/sdk/src/physics/index.ts
+++ b/sdk/src/physics/index.ts
@@ -71,6 +71,17 @@ export {
type PhysicsDebugDrawConfig,
} from './PhysicsDebugDraw';
+export {
+ readColliderShapes,
+ shapeOffset,
+ shapeCenter,
+ colliderShapeOutline,
+ CAPSULE_ARC_SEGMENTS,
+ type ColliderShape,
+ type ColliderInstance,
+ type ColliderOutline,
+} from './ColliderShape';
+
export {
CharacterController,
moveAndSlide,
diff --git a/sdk/tests/collider-shape.test.ts b/sdk/tests/collider-shape.test.ts
new file mode 100644
index 000000000..0ecbde7c3
--- /dev/null
+++ b/sdk/tests/collider-shape.test.ts
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * Golden geometry for the shared collider-shape projection. The outlines must match the
+ * pre-refactor PhysicsDebugDraw math exactly (this is the Phase-0 parity proof) so both
+ * the runtime debug draw and the editor gizmo can render from one source.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ shapeCenter, colliderShapeOutline, CAPSULE_ARC_SEGMENTS,
+ type ColliderShape,
+} from '../src/physics/ColliderShape';
+
+const near = (a: { x: number; y: number }, x: number, y: number) => {
+ expect(a.x).toBeCloseTo(x, 6);
+ expect(a.y).toBeCloseTo(y, 6);
+};
+
+describe('shapeCenter', () => {
+ it('adds the collider offset (metres × ppu), unrotated', () => {
+ const box: ColliderShape = { kind: 'box', halfExtents: { x: 0.5, y: 0.5 }, offset: { x: 1, y: 0 } };
+ near(shapeCenter(box, { x: 10, y: 20 }, 0, 100), 110, 20);
+ });
+ it('rotates the offset by the entity angle', () => {
+ const box: ColliderShape = { kind: 'box', halfExtents: { x: 0.5, y: 0.5 }, offset: { x: 1, y: 0 } };
+ near(shapeCenter(box, { x: 10, y: 20 }, Math.PI / 2, 100), 10, 120); // (100,0) rotated 90° → (0,100)
+ });
+ it('is the entity position for offsetless shapes (segment/polygon/chain)', () => {
+ const seg: ColliderShape = { kind: 'segment', point1: { x: -0.5, y: 0 }, point2: { x: 0.5, y: 0 } };
+ near(shapeCenter(seg, { x: 7, y: 9 }, 1.234, 100), 7, 9);
+ });
+});
+
+describe('colliderShapeOutline', () => {
+ it('box → a closed 4-corner loop, ppu-scaled', () => {
+ const box: ColliderShape = { kind: 'box', halfExtents: { x: 0.5, y: 0.5 }, offset: { x: 0, y: 0 } };
+ const o = colliderShapeOutline(box, { x: 0, y: 0 }, 0, 100);
+ expect(o.circles).toEqual([]);
+ expect(o.polylines).toHaveLength(1);
+ const p = o.polylines[0];
+ expect(p).toHaveLength(5); // 4 corners + closing point
+ near(p[0], -50, -50); near(p[1], 50, -50); near(p[2], 50, 50); near(p[3], -50, 50);
+ near(p[4], p[0].x, p[0].y);
+ });
+
+ it('box corners match the legacy drawRotatedBox math under rotation', () => {
+ const hx = 40, hy = 20, angle = 0.7, cx = 12, cy = -3;
+ const box: ColliderShape = { kind: 'box', halfExtents: { x: hx / 100, y: hy / 100 }, offset: { x: 0, y: 0 } };
+ const p = colliderShapeOutline(box, { x: cx, y: cy }, angle, 100).polylines[0];
+ // Reference: the exact transform the old drawRotatedBox used.
+ const cos = Math.cos(angle), sin = Math.sin(angle);
+ const corners = [[-hx, -hy], [hx, -hy], [hx, hy], [-hx, hy]] as const;
+ corners.forEach(([lx, ly], i) => near(p[i], cx + lx * cos - ly * sin, cy + lx * sin + ly * cos));
+ });
+
+ it('circle → a single {c,r}, no polylines', () => {
+ const c: ColliderShape = { kind: 'circle', radius: 0.5, offset: { x: 0, y: 0 } };
+ const o = colliderShapeOutline(c, { x: 5, y: 5 }, 0, 100);
+ expect(o.polylines).toEqual([]);
+ expect(o.circles).toHaveLength(1);
+ near(o.circles[0].c, 5, 5);
+ expect(o.circles[0].r).toBeCloseTo(50, 6);
+ });
+
+ it('capsule → one closed loop with the same segment count the legacy draw emitted', () => {
+ const cap: ColliderShape = { kind: 'capsule', radius: 0.25, halfHeight: 0.5, offset: { x: 0, y: 0 } };
+ const o = colliderShapeOutline(cap, { x: 0, y: 0 }, 0, 100);
+ expect(o.circles).toEqual([]);
+ // legacy: 2 side lines + 2 arcs (16 segs each) = 2 + 32 = 34 segments = 35 points.
+ const pts = o.polylines[0];
+ expect(pts).toHaveLength(2 + 2 * CAPSULE_ARC_SEGMENTS + 1);
+ expect(pts.length - 1).toBe(2 + 2 * CAPSULE_ARC_SEGMENTS); // 34 segments
+ near(pts[0], -25, -50); // bottomLeft
+ near(pts[1], -25, 50); // topLeft
+ near(pts[pts.length - 1], -25, -50); // closes back to bottomLeft
+ });
+
+ it('segment → one open two-point polyline', () => {
+ const seg: ColliderShape = { kind: 'segment', point1: { x: -0.5, y: 0 }, point2: { x: 0.5, y: 0 } };
+ const o = colliderShapeOutline(seg, { x: 0, y: 0 }, 0, 100);
+ expect(o.polylines).toHaveLength(1);
+ expect(o.polylines[0]).toHaveLength(2);
+ near(o.polylines[0][0], -50, 0); near(o.polylines[0][1], 50, 0);
+ });
+
+ it('polygon → a closed loop of n+1 points', () => {
+ const poly: ColliderShape = { kind: 'polygon', vertices: [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 0, y: 1 }] };
+ const p = colliderShapeOutline(poly, { x: 0, y: 0 }, 0, 100).polylines[0];
+ expect(p).toHaveLength(4);
+ near(p[0], 0, 0); near(p[1], 100, 0); near(p[2], 0, 100); near(p[3], 0, 0);
+ });
+
+ it('chain → open by default, closed when isLoop', () => {
+ const pts = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }];
+ const open = colliderShapeOutline({ kind: 'chain', points: pts, isLoop: false }, { x: 0, y: 0 }, 0, 100);
+ expect(open.polylines[0]).toHaveLength(3); // 2 segments
+ const loop = colliderShapeOutline({ kind: 'chain', points: pts, isLoop: true }, { x: 0, y: 0 }, 0, 100);
+ expect(loop.polylines[0]).toHaveLength(4); // 3 segments (closed)
+ });
+
+ it('degenerate chain (<2 points) draws nothing', () => {
+ const o = colliderShapeOutline({ kind: 'chain', points: [{ x: 0, y: 0 }], isLoop: false }, { x: 0, y: 0 }, 0, 100);
+ expect(o.polylines).toEqual([]);
+ });
+});