@codexo/exojs-tilemap-physics 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +166 -0
- package/dist/esm/TileColliderStreamer.d.ts +98 -0
- package/dist/esm/TileColliderStreamer.d.ts.map +1 -0
- package/dist/esm/TileColliderStreamer.js +191 -0
- package/dist/esm/TileColliderStreamer.js.map +1 -0
- package/dist/esm/buildColliders.d.ts +53 -0
- package/dist/esm/buildColliders.d.ts.map +1 -0
- package/dist/esm/buildColliders.js +226 -0
- package/dist/esm/buildColliders.js.map +1 -0
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +4 -0
- package/dist/esm/material.d.ts +25 -0
- package/dist/esm/material.d.ts.map +1 -0
- package/dist/esm/material.js +48 -0
- package/dist/esm/material.js.map +1 -0
- package/dist/esm/objectLayer.d.ts +29 -0
- package/dist/esm/objectLayer.d.ts.map +1 -0
- package/dist/esm/objectLayer.js +55 -0
- package/dist/esm/objectLayer.js.map +1 -0
- package/dist/esm/outline.d.ts +14 -0
- package/dist/esm/outline.d.ts.map +1 -0
- package/dist/esm/outline.js +190 -0
- package/dist/esm/outline.js.map +1 -0
- package/dist/esm/public.d.ts +6 -0
- package/dist/esm/public.d.ts.map +1 -0
- package/dist/esm/types.d.ts +70 -0
- package/dist/esm/types.d.ts.map +1 -0
- package/package.json +52 -0
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { materialKey, resolveMaterial } from "./material.js";
|
|
2
|
+
import { traceCellOutlines } from "./outline.js";
|
|
3
|
+
import { BoxShape, CapsuleShape, ChainShape, CircleShape, toConvexPolygonShapes } from "@codexo/exojs-physics";
|
|
4
|
+
import { logger } from "@codexo/exojs";
|
|
5
|
+
import { ObjectKind } from "@codexo/exojs-tilemap";
|
|
6
|
+
|
|
7
|
+
//#region src/buildColliders.ts
|
|
8
|
+
const DEGREES_TO_RADIANS = Math.PI / 180;
|
|
9
|
+
/** Shortest capsule spine `CapsuleShape` accepts; below it, the shape is a circle. */
|
|
10
|
+
const MINIMUM_SPINE = .001;
|
|
11
|
+
const LOG_SOURCE = "tilemap-physics";
|
|
12
|
+
const applyMaterial = (material) => ({
|
|
13
|
+
friction: material.friction,
|
|
14
|
+
restitution: material.restitution,
|
|
15
|
+
density: material.density,
|
|
16
|
+
isSensor: material.isSensor,
|
|
17
|
+
filter: material.filter
|
|
18
|
+
});
|
|
19
|
+
/** Centre of an axis-aligned box rotated about its own top-left origin. */
|
|
20
|
+
const rotatedCentre = (x, y, width, height, angle) => {
|
|
21
|
+
const cos = Math.cos(angle);
|
|
22
|
+
const sin = Math.sin(angle);
|
|
23
|
+
return {
|
|
24
|
+
x: x + (cos * (width / 2) - sin * (height / 2)),
|
|
25
|
+
y: y + (sin * (width / 2) + cos * (height / 2))
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* The tightest conservative cover of an ellipse the shape set offers: a capsule
|
|
30
|
+
* whose radius is the minor semi-axis and whose spine runs the difference of the
|
|
31
|
+
* semi-axes along the major axis. Every ellipse point is within the minor
|
|
32
|
+
* semi-axis of that spine, and the capsule is itself inside the circumscribed
|
|
33
|
+
* circle, so it covers the ellipse and is never worse than the circle. A round
|
|
34
|
+
* ellipse degenerates to that circle.
|
|
35
|
+
*/
|
|
36
|
+
const ellipseShape = (width, height) => {
|
|
37
|
+
const semiMajor = Math.max(width, height) / 2;
|
|
38
|
+
const semiMinor = Math.min(width, height) / 2;
|
|
39
|
+
if (semiMinor <= 0) return null;
|
|
40
|
+
const spine = 2 * (semiMajor - semiMinor);
|
|
41
|
+
if (spine < MINIMUM_SPINE) return new CircleShape(semiMinor);
|
|
42
|
+
return width >= height ? new CapsuleShape(-spine / 2, 0, spine / 2, 0, semiMinor) : new CapsuleShape(0, -spine / 2, 0, spine / 2, semiMinor);
|
|
43
|
+
};
|
|
44
|
+
/** `true` when a polyline's endpoints coincide, i.e. the author drew a loop. */
|
|
45
|
+
const isClosedRun = (points) => {
|
|
46
|
+
const first = points.at(0);
|
|
47
|
+
const last = points.at(-1);
|
|
48
|
+
return points.length > 2 && first !== void 0 && first.x === last?.x && first.y === last.y;
|
|
49
|
+
};
|
|
50
|
+
const describe = (error) => error instanceof Error ? error.message : String(error);
|
|
51
|
+
/**
|
|
52
|
+
* Map one piece of collision geometry to the colliders that represent it, in
|
|
53
|
+
* the owning body's local space.
|
|
54
|
+
*
|
|
55
|
+
* A concave polygon becomes several convex colliders on the same body; a
|
|
56
|
+
* polygon the decomposition rejects is skipped with a warning rather than
|
|
57
|
+
* failing the whole build, because level geometry is content, not code.
|
|
58
|
+
*/
|
|
59
|
+
const collidersForGeometry = (geometry, material, originX, originY, label) => {
|
|
60
|
+
const rotation = geometry.rotation * DEGREES_TO_RADIANS;
|
|
61
|
+
const settings = applyMaterial(material);
|
|
62
|
+
switch (geometry.kind) {
|
|
63
|
+
case ObjectKind.Rectangle: {
|
|
64
|
+
if (geometry.width <= 0 || geometry.height <= 0) return [];
|
|
65
|
+
const centre = rotatedCentre(geometry.x, geometry.y, geometry.width, geometry.height, rotation);
|
|
66
|
+
return [{
|
|
67
|
+
shape: new BoxShape(geometry.width, geometry.height),
|
|
68
|
+
offset: {
|
|
69
|
+
x: centre.x - originX,
|
|
70
|
+
y: centre.y - originY
|
|
71
|
+
},
|
|
72
|
+
rotation,
|
|
73
|
+
...settings
|
|
74
|
+
}];
|
|
75
|
+
}
|
|
76
|
+
case ObjectKind.Ellipse: {
|
|
77
|
+
const shape = ellipseShape(geometry.width, geometry.height);
|
|
78
|
+
if (shape === null) return [];
|
|
79
|
+
const centre = rotatedCentre(geometry.x, geometry.y, geometry.width, geometry.height, rotation);
|
|
80
|
+
return [{
|
|
81
|
+
shape,
|
|
82
|
+
offset: {
|
|
83
|
+
x: centre.x - originX,
|
|
84
|
+
y: centre.y - originY
|
|
85
|
+
},
|
|
86
|
+
rotation,
|
|
87
|
+
...settings
|
|
88
|
+
}];
|
|
89
|
+
}
|
|
90
|
+
case ObjectKind.Polygon: {
|
|
91
|
+
const points = geometry.points ?? [];
|
|
92
|
+
if (points.length < 3) return [];
|
|
93
|
+
const offset = {
|
|
94
|
+
x: geometry.x - originX,
|
|
95
|
+
y: geometry.y - originY
|
|
96
|
+
};
|
|
97
|
+
try {
|
|
98
|
+
return toConvexPolygonShapes(points).map((shape) => ({
|
|
99
|
+
shape,
|
|
100
|
+
offset,
|
|
101
|
+
rotation,
|
|
102
|
+
...settings
|
|
103
|
+
}));
|
|
104
|
+
} catch (error) {
|
|
105
|
+
logger.warn(`Skipped polygon "${label}": ${describe(error)}`, { source: LOG_SOURCE });
|
|
106
|
+
return [];
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
case ObjectKind.Polyline: {
|
|
110
|
+
const points = geometry.points ?? [];
|
|
111
|
+
const closed = isClosedRun(points);
|
|
112
|
+
const run = closed ? points.slice(0, -1) : points;
|
|
113
|
+
if (run.length < 2) return [];
|
|
114
|
+
const offset = {
|
|
115
|
+
x: geometry.x - originX,
|
|
116
|
+
y: geometry.y - originY
|
|
117
|
+
};
|
|
118
|
+
try {
|
|
119
|
+
return [{
|
|
120
|
+
shape: new ChainShape(run, { closed }),
|
|
121
|
+
offset,
|
|
122
|
+
rotation,
|
|
123
|
+
...settings
|
|
124
|
+
}];
|
|
125
|
+
} catch (error) {
|
|
126
|
+
logger.warn(`Skipped polyline "${label}": ${describe(error)}`, { source: LOG_SOURCE });
|
|
127
|
+
return [];
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
case ObjectKind.Point:
|
|
131
|
+
case ObjectKind.Tile:
|
|
132
|
+
case ObjectKind.Text:
|
|
133
|
+
default: return [];
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
/** Tile column/row of a merged rectangle's top-left cell. */
|
|
137
|
+
const rectCell = (rect, options) => ({
|
|
138
|
+
tx: Math.round((rect.x - options.layerOffsetX) / options.tileWidth),
|
|
139
|
+
ty: Math.round((rect.y - options.layerOffsetY) / options.tileHeight)
|
|
140
|
+
});
|
|
141
|
+
const boxForRect = (rect, material, originX, originY) => ({
|
|
142
|
+
shape: new BoxShape(rect.width, rect.height),
|
|
143
|
+
offset: {
|
|
144
|
+
x: rect.x + rect.width / 2 - originX,
|
|
145
|
+
y: rect.y + rect.height / 2 - originY
|
|
146
|
+
},
|
|
147
|
+
...applyMaterial(material)
|
|
148
|
+
});
|
|
149
|
+
/**
|
|
150
|
+
* Chains for every merged rectangle, grouped by resolved collider semantics:
|
|
151
|
+
* cells whose colliders would be indistinguishable are traced into one
|
|
152
|
+
* boundary, and cells that resolve differently keep their own.
|
|
153
|
+
*/
|
|
154
|
+
const chainsForRects = (regions, options, originX, originY) => {
|
|
155
|
+
const groups = /* @__PURE__ */ new Map();
|
|
156
|
+
for (const { rect, material } of regions) {
|
|
157
|
+
const groupKey = materialKey(material);
|
|
158
|
+
let group = groups.get(groupKey);
|
|
159
|
+
if (group === void 0) {
|
|
160
|
+
group = {
|
|
161
|
+
material,
|
|
162
|
+
cells: []
|
|
163
|
+
};
|
|
164
|
+
groups.set(groupKey, group);
|
|
165
|
+
}
|
|
166
|
+
const { tx, ty } = rectCell(rect, options);
|
|
167
|
+
const columns = Math.round(rect.width / options.tileWidth);
|
|
168
|
+
const rows = Math.round(rect.height / options.tileHeight);
|
|
169
|
+
for (let row = 0; row < rows; row++) for (let column = 0; column < columns; column++) group.cells.push(tx + column, ty + row);
|
|
170
|
+
}
|
|
171
|
+
const colliders = [];
|
|
172
|
+
for (const group of groups.values()) {
|
|
173
|
+
const settings = applyMaterial(group.material);
|
|
174
|
+
for (const loop of traceCellOutlines(group.cells)) {
|
|
175
|
+
const vertices = loop.map((vertex) => ({
|
|
176
|
+
x: vertex.x * options.tileWidth + options.layerOffsetX - originX,
|
|
177
|
+
y: vertex.y * options.tileHeight + options.layerOffsetY - originY
|
|
178
|
+
}));
|
|
179
|
+
colliders.push({
|
|
180
|
+
shape: new ChainShape(vertices, { closed: true }),
|
|
181
|
+
...settings
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return colliders;
|
|
186
|
+
};
|
|
187
|
+
const shapeLabel = (shape) => shape.source.name || `tile ${shape.tx},${shape.ty}`;
|
|
188
|
+
const objectLabel = (object) => object.name || String(object.id);
|
|
189
|
+
/**
|
|
190
|
+
* Turn extracted tile-collision geometry into the colliders of a single body
|
|
191
|
+
* placed at `(options.x, options.y)` in layer pixel space.
|
|
192
|
+
*
|
|
193
|
+
* Order is contractual: merged regions first in the order the extraction emits
|
|
194
|
+
* them, then per-tile shapes in tile walk order.
|
|
195
|
+
*/
|
|
196
|
+
const buildTileColliders = (geometry, options) => {
|
|
197
|
+
const originX = options.x;
|
|
198
|
+
const originY = options.y;
|
|
199
|
+
const regions = geometry.rects.map((rect) => {
|
|
200
|
+
const { tx, ty } = rectCell(rect, options);
|
|
201
|
+
return {
|
|
202
|
+
rect,
|
|
203
|
+
material: resolveMaterial(options.defaults, options.material, {
|
|
204
|
+
type: rect.type,
|
|
205
|
+
object: null,
|
|
206
|
+
tx,
|
|
207
|
+
ty
|
|
208
|
+
})
|
|
209
|
+
};
|
|
210
|
+
});
|
|
211
|
+
const colliders = options.regionMode === "outline" ? chainsForRects(regions, options, originX, originY) : regions.map(({ rect, material }) => boxForRect(rect, material, originX, originY));
|
|
212
|
+
for (const shape of geometry.shapes) {
|
|
213
|
+
const material = resolveMaterial(options.defaults, options.material, {
|
|
214
|
+
type: shape.source.type,
|
|
215
|
+
object: shape.source,
|
|
216
|
+
tx: shape.tx,
|
|
217
|
+
ty: shape.ty
|
|
218
|
+
});
|
|
219
|
+
colliders.push(...collidersForGeometry(shape, material, originX, originY, shapeLabel(shape)));
|
|
220
|
+
}
|
|
221
|
+
return colliders;
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
//#endregion
|
|
225
|
+
export { buildTileColliders, collidersForGeometry, objectLabel };
|
|
226
|
+
//# sourceMappingURL=buildColliders.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"buildColliders.js","names":[],"sources":["../../src/buildColliders.ts"],"sourcesContent":["import { logger, type PointLike } from '@codexo/exojs';\nimport { BoxShape, CapsuleShape, ChainShape, CircleShape, type ColliderOptions, toConvexPolygonShapes } from '@codexo/exojs-physics';\nimport { ObjectKind, type TileCollisionGeometry, type TileCollisionRect, type TileCollisionShape, type TileMapObject } from '@codexo/exojs-tilemap';\n\nimport { materialKey, type ResolvedMaterial, resolveMaterial } from './material';\nimport { traceCellOutlines } from './outline';\nimport type { TileColliderMaterialResolver, TileRegionMode } from './types';\n\nconst DEGREES_TO_RADIANS = Math.PI / 180;\n\n/** Shortest capsule spine `CapsuleShape` accepts; below it, the shape is a circle. */\nconst MINIMUM_SPINE = 1e-3;\n\nconst LOG_SOURCE = 'tilemap-physics';\n\n/** Placement of one piece of geometry in the owning body's local space. */\nexport interface ColliderPlacement {\n readonly x: number;\n readonly y: number;\n readonly tileWidth: number;\n readonly tileHeight: number;\n readonly layerOffsetX: number;\n readonly layerOffsetY: number;\n}\n\n/** Everything a build needs beyond the geometry itself. */\nexport interface ColliderBuildOptions extends ColliderPlacement {\n readonly regionMode: TileRegionMode;\n readonly defaults: ResolvedMaterial;\n readonly material: TileColliderMaterialResolver | undefined;\n}\n\nconst applyMaterial = (material: ResolvedMaterial): Omit<ColliderOptions, 'shape'> => ({\n friction: material.friction,\n restitution: material.restitution,\n density: material.density,\n isSensor: material.isSensor,\n filter: material.filter,\n});\n\n/** Centre of an axis-aligned box rotated about its own top-left origin. */\nconst rotatedCentre = (x: number, y: number, width: number, height: number, angle: number): PointLike => {\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n\n return {\n x: x + (cos * (width / 2) - sin * (height / 2)),\n y: y + (sin * (width / 2) + cos * (height / 2)),\n };\n};\n\n/**\n * The tightest conservative cover of an ellipse the shape set offers: a capsule\n * whose radius is the minor semi-axis and whose spine runs the difference of the\n * semi-axes along the major axis. Every ellipse point is within the minor\n * semi-axis of that spine, and the capsule is itself inside the circumscribed\n * circle, so it covers the ellipse and is never worse than the circle. A round\n * ellipse degenerates to that circle.\n */\nconst ellipseShape = (width: number, height: number): BoxShape | CapsuleShape | CircleShape | null => {\n const semiMajor = Math.max(width, height) / 2;\n const semiMinor = Math.min(width, height) / 2;\n\n if (semiMinor <= 0) {\n return null;\n }\n\n const spine = 2 * (semiMajor - semiMinor);\n\n if (spine < MINIMUM_SPINE) {\n return new CircleShape(semiMinor);\n }\n\n return width >= height ? new CapsuleShape(-spine / 2, 0, spine / 2, 0, semiMinor) : new CapsuleShape(0, -spine / 2, 0, spine / 2, semiMinor);\n};\n\n/** `true` when a polyline's endpoints coincide, i.e. the author drew a loop. */\nconst isClosedRun = (points: readonly PointLike[]): boolean => {\n const first = points.at(0);\n const last = points.at(-1);\n\n return points.length > 2 && first !== undefined && first.x === last?.x && first.y === last.y;\n};\n\nconst describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\n/**\n * The fields an object-layer object and a per-tile collision shape share -\n * enough to pick a shape. Both are structurally assignable to it.\n */\nexport interface CollisionGeometry {\n readonly kind: ObjectKind;\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n readonly rotation: number;\n readonly points?: readonly PointLike[];\n}\n\n/**\n * Map one piece of collision geometry to the colliders that represent it, in\n * the owning body's local space.\n *\n * A concave polygon becomes several convex colliders on the same body; a\n * polygon the decomposition rejects is skipped with a warning rather than\n * failing the whole build, because level geometry is content, not code.\n */\nexport const collidersForGeometry = (\n geometry: CollisionGeometry,\n material: ResolvedMaterial,\n originX: number,\n originY: number,\n label: string,\n): ColliderOptions[] => {\n const rotation = geometry.rotation * DEGREES_TO_RADIANS;\n const settings = applyMaterial(material);\n\n switch (geometry.kind) {\n case ObjectKind.Rectangle: {\n if (geometry.width <= 0 || geometry.height <= 0) {\n return [];\n }\n\n const centre = rotatedCentre(geometry.x, geometry.y, geometry.width, geometry.height, rotation);\n\n return [\n {\n shape: new BoxShape(geometry.width, geometry.height),\n offset: { x: centre.x - originX, y: centre.y - originY },\n rotation,\n ...settings,\n },\n ];\n }\n\n case ObjectKind.Ellipse: {\n const shape = ellipseShape(geometry.width, geometry.height);\n\n if (shape === null) {\n return [];\n }\n\n const centre = rotatedCentre(geometry.x, geometry.y, geometry.width, geometry.height, rotation);\n\n return [{ shape, offset: { x: centre.x - originX, y: centre.y - originY }, rotation, ...settings }];\n }\n\n case ObjectKind.Polygon: {\n const points = geometry.points ?? [];\n\n if (points.length < 3) {\n return [];\n }\n\n const offset = { x: geometry.x - originX, y: geometry.y - originY };\n\n try {\n return toConvexPolygonShapes(points).map(shape => ({ shape, offset, rotation, ...settings }));\n } catch (error) {\n logger.warn(`Skipped polygon \"${label}\": ${describe(error)}`, { source: LOG_SOURCE });\n\n return [];\n }\n }\n\n case ObjectKind.Polyline: {\n const points = geometry.points ?? [];\n const closed = isClosedRun(points);\n const run = closed ? points.slice(0, -1) : points;\n\n if (run.length < 2) {\n return [];\n }\n\n const offset = { x: geometry.x - originX, y: geometry.y - originY };\n\n try {\n return [{ shape: new ChainShape(run, { closed }), offset, rotation, ...settings }];\n } catch (error) {\n logger.warn(`Skipped polyline \"${label}\": ${describe(error)}`, { source: LOG_SOURCE });\n\n return [];\n }\n }\n\n case ObjectKind.Point:\n case ObjectKind.Tile:\n case ObjectKind.Text:\n default:\n // Points carry no area and no boundary; tile and text objects never reach\n // here - the geometry extraction excludes them.\n return [];\n }\n};\n\n/** Tile column/row of a merged rectangle's top-left cell. */\nconst rectCell = (rect: TileCollisionRect, options: ColliderPlacement): { tx: number; ty: number } => ({\n tx: Math.round((rect.x - options.layerOffsetX) / options.tileWidth),\n ty: Math.round((rect.y - options.layerOffsetY) / options.tileHeight),\n});\n\nconst boxForRect = (rect: TileCollisionRect, material: ResolvedMaterial, originX: number, originY: number): ColliderOptions => ({\n shape: new BoxShape(rect.width, rect.height),\n offset: { x: rect.x + rect.width / 2 - originX, y: rect.y + rect.height / 2 - originY },\n ...applyMaterial(material),\n});\n\n/** A merged rectangle together with the material its colliders resolve to. */\ninterface ResolvedRect {\n readonly rect: TileCollisionRect;\n readonly material: ResolvedMaterial;\n}\n\n/**\n * Chains for every merged rectangle, grouped by resolved collider semantics:\n * cells whose colliders would be indistinguishable are traced into one\n * boundary, and cells that resolve differently keep their own.\n */\nconst chainsForRects = (regions: readonly ResolvedRect[], options: ColliderBuildOptions, originX: number, originY: number): ColliderOptions[] => {\n const groups = new Map<string, { material: ResolvedMaterial; cells: number[] }>();\n\n for (const { rect, material } of regions) {\n const groupKey = materialKey(material);\n let group = groups.get(groupKey);\n\n if (group === undefined) {\n group = { material, cells: [] };\n groups.set(groupKey, group);\n }\n\n const { tx, ty } = rectCell(rect, options);\n const columns = Math.round(rect.width / options.tileWidth);\n const rows = Math.round(rect.height / options.tileHeight);\n\n for (let row = 0; row < rows; row++) {\n for (let column = 0; column < columns; column++) {\n group.cells.push(tx + column, ty + row);\n }\n }\n }\n\n const colliders: ColliderOptions[] = [];\n\n for (const group of groups.values()) {\n const settings = applyMaterial(group.material);\n\n for (const loop of traceCellOutlines(group.cells)) {\n const vertices = loop.map(vertex => ({\n x: vertex.x * options.tileWidth + options.layerOffsetX - originX,\n y: vertex.y * options.tileHeight + options.layerOffsetY - originY,\n }));\n\n colliders.push({ shape: new ChainShape(vertices, { closed: true }), ...settings });\n }\n }\n\n return colliders;\n};\n\nconst shapeLabel = (shape: TileCollisionShape): string => shape.source.name || `tile ${shape.tx},${shape.ty}`;\n\nconst objectLabel = (object: TileMapObject): string => object.name || String(object.id);\n\nexport { objectLabel };\n\n/**\n * Turn extracted tile-collision geometry into the colliders of a single body\n * placed at `(options.x, options.y)` in layer pixel space.\n *\n * Order is contractual: merged regions first in the order the extraction emits\n * them, then per-tile shapes in tile walk order.\n */\nexport const buildTileColliders = (geometry: TileCollisionGeometry, options: ColliderBuildOptions): ColliderOptions[] => {\n const originX = options.x;\n const originY = options.y;\n const regions: ResolvedRect[] = geometry.rects.map(rect => {\n const { tx, ty } = rectCell(rect, options);\n\n return {\n rect,\n material: resolveMaterial(options.defaults, options.material, { type: rect.type, object: null, tx, ty }),\n };\n });\n\n const colliders: ColliderOptions[] =\n options.regionMode === 'outline'\n ? chainsForRects(regions, options, originX, originY)\n : regions.map(({ rect, material }) => boxForRect(rect, material, originX, originY));\n\n for (const shape of geometry.shapes) {\n const material = resolveMaterial(options.defaults, options.material, {\n type: shape.source.type,\n object: shape.source,\n tx: shape.tx,\n ty: shape.ty,\n });\n\n colliders.push(...collidersForGeometry(shape, material, originX, originY, shapeLabel(shape)));\n }\n\n return colliders;\n};\n"],"mappings":";;;;;;;AAQA,MAAM,qBAAqB,KAAK,KAAK;;AAGrC,MAAM,gBAAgB;AAEtB,MAAM,aAAa;AAmBnB,MAAM,iBAAiB,cAAgE;CACrF,UAAU,SAAS;CACnB,aAAa,SAAS;CACtB,SAAS,SAAS;CAClB,UAAU,SAAS;CACnB,QAAQ,SAAS;AACnB;;AAGA,MAAM,iBAAiB,GAAW,GAAW,OAAe,QAAgB,UAA6B;CACvG,MAAM,MAAM,KAAK,IAAI,KAAK;CAC1B,MAAM,MAAM,KAAK,IAAI,KAAK;CAE1B,OAAO;EACL,GAAG,KAAK,OAAO,QAAQ,KAAK,OAAO,SAAS;EAC5C,GAAG,KAAK,OAAO,QAAQ,KAAK,OAAO,SAAS;CAC9C;AACF;;;;;;;;;AAUA,MAAM,gBAAgB,OAAe,WAAiE;CACpG,MAAM,YAAY,KAAK,IAAI,OAAO,MAAM,IAAI;CAC5C,MAAM,YAAY,KAAK,IAAI,OAAO,MAAM,IAAI;CAE5C,IAAI,aAAa,GACf,OAAO;CAGT,MAAM,QAAQ,KAAK,YAAY;CAE/B,IAAI,QAAQ,eACV,OAAO,IAAI,YAAY,SAAS;CAGlC,OAAO,SAAS,SAAS,IAAI,aAAa,CAAC,QAAQ,GAAG,GAAG,QAAQ,GAAG,GAAG,SAAS,I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AAO,OAAO,EAAE;;;;;;;;AAWtF,MAAa,sBAAsB,UAAiC,YAAqD;CACvH,MAAM,UAAU,QAAQ;CACxB,MAAM,UAAU,QAAQ;CACxB,MAAM,UAA0B,SAAS,MAAM,KAAI,SAAQ;EACzD,MAAM,EAAE,IAAI,OAAO,SAAS,MAAM,OAAO;EAEzC,OAAO;GACL;GACA,UAAU,gBAAgB,QAAQ,UAAU,QAAQ,UAAU;IAAE,MAAM,KAAK;IAAM,QAAQ;IAAM;IAAI;GAAG,CAAC;EACzG;CACF,CAAC;CAED,MAAM,YACJ,QAAQ,eAAe,YACnB,eAAe,SAAS,SAAS,SAAS,OAAO,IACjD,QAAQ,KAAK,EAAE,MAAM,eAAe,WAAW,MAAM,UAAU,SAAS,OAAO,CAAC;CAEtF,KAAK,MAAM,SAAS,SAAS,QAAQ;EACnC,MAAM,WAAW,gBAAgB,QAAQ,UAAU,QAAQ,UAAU;GACnE,MAAM,MAAM,OAAO;GACnB,QAAQ,MAAM;GACd,IAAI,MAAM;GACV,IAAI,MAAM;EACZ,CAAC;EAED,UAAU,KAAK,GAAG,qBAAqB,OAAO,UAAU,SAAS,SAAS,WAAW,KAAK,CAAC,CAAC;CAC9F;CAEA,OAAO;AACT"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,cAAc,UAAU,CAAC"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type CollisionFilter } from '@codexo/exojs-physics';
|
|
2
|
+
import type { ColliderDefaults, TileColliderContext } from './types';
|
|
3
|
+
/** A fully resolved collider material: every field decided, nothing optional. */
|
|
4
|
+
export interface ResolvedMaterial {
|
|
5
|
+
readonly friction: number;
|
|
6
|
+
readonly restitution: number;
|
|
7
|
+
readonly density: number;
|
|
8
|
+
readonly isSensor: boolean;
|
|
9
|
+
readonly filter: CollisionFilter;
|
|
10
|
+
}
|
|
11
|
+
/** Resolve the call-level defaults once, before any geometry is walked. */
|
|
12
|
+
export declare const resolveDefaults: (options: ColliderDefaults) => ResolvedMaterial;
|
|
13
|
+
/** Apply a resolver's overrides over already-resolved defaults. */
|
|
14
|
+
export declare const resolveMaterial: (defaults: ResolvedMaterial, resolver: ColliderDefaults["material"], context: TileColliderContext) => ResolvedMaterial;
|
|
15
|
+
/**
|
|
16
|
+
* Identity of everything a chain collider can carry, used to decide which solid
|
|
17
|
+
* cells may be traced into a common outline.
|
|
18
|
+
*
|
|
19
|
+
* `density` is deliberately absent: a chain has no mass properties and the
|
|
20
|
+
* bodies are static, so two regions differing only in density are
|
|
21
|
+
* indistinguishable once built, and keying on it would split outlines for no
|
|
22
|
+
* observable difference.
|
|
23
|
+
*/
|
|
24
|
+
export declare const materialKey: (material: ResolvedMaterial) => string;
|
|
25
|
+
//# sourceMappingURL=material.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"material.d.ts","sourceRoot":"","sources":["../../src/material.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,eAAe,EAAiB,MAAM,uBAAuB,CAAC;AAE5E,OAAO,KAAK,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAMrE,iFAAiF;AACjF,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC;CAClC;AAED,2EAA2E;AAC3E,eAAO,MAAM,eAAe,GAAI,SAAS,gBAAgB,KAAG,gBAU1D,CAAC;AAEH,mEAAmE;AACnE,eAAO,MAAM,eAAe,GAAI,UAAU,gBAAgB,EAAE,UAAU,gBAAgB,CAAC,UAAU,CAAC,EAAE,SAAS,mBAAmB,KAAG,gBAkBlI,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,GAAI,UAAU,gBAAgB,KAAG,MACiG,CAAC"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { defaultFilter } from "@codexo/exojs-physics";
|
|
2
|
+
|
|
3
|
+
//#region src/material.ts
|
|
4
|
+
const DEFAULT_FRICTION = .6;
|
|
5
|
+
const DEFAULT_RESTITUTION = 0;
|
|
6
|
+
const DEFAULT_DENSITY = 1;
|
|
7
|
+
/** Resolve the call-level defaults once, before any geometry is walked. */
|
|
8
|
+
const resolveDefaults = (options) => ({
|
|
9
|
+
friction: options.friction ?? DEFAULT_FRICTION,
|
|
10
|
+
restitution: options.restitution ?? DEFAULT_RESTITUTION,
|
|
11
|
+
density: options.density ?? DEFAULT_DENSITY,
|
|
12
|
+
isSensor: options.isSensor ?? false,
|
|
13
|
+
filter: {
|
|
14
|
+
category: options.filter?.category ?? defaultFilter.category,
|
|
15
|
+
mask: options.filter?.mask ?? defaultFilter.mask,
|
|
16
|
+
group: options.filter?.group ?? defaultFilter.group
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
/** Apply a resolver's overrides over already-resolved defaults. */
|
|
20
|
+
const resolveMaterial = (defaults, resolver, context) => {
|
|
21
|
+
const override = resolver?.(context);
|
|
22
|
+
if (override === void 0 || override === null) return defaults;
|
|
23
|
+
return {
|
|
24
|
+
friction: override.friction ?? defaults.friction,
|
|
25
|
+
restitution: override.restitution ?? defaults.restitution,
|
|
26
|
+
density: override.density ?? defaults.density,
|
|
27
|
+
isSensor: override.isSensor ?? defaults.isSensor,
|
|
28
|
+
filter: {
|
|
29
|
+
category: override.filter?.category ?? defaults.filter.category,
|
|
30
|
+
mask: override.filter?.mask ?? defaults.filter.mask,
|
|
31
|
+
group: override.filter?.group ?? defaults.filter.group
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Identity of everything a chain collider can carry, used to decide which solid
|
|
37
|
+
* cells may be traced into a common outline.
|
|
38
|
+
*
|
|
39
|
+
* `density` is deliberately absent: a chain has no mass properties and the
|
|
40
|
+
* bodies are static, so two regions differing only in density are
|
|
41
|
+
* indistinguishable once built, and keying on it would split outlines for no
|
|
42
|
+
* observable difference.
|
|
43
|
+
*/
|
|
44
|
+
const materialKey = (material) => `${material.friction}|${material.restitution}|${material.isSensor ? 1 : 0}|${material.filter.category}|${material.filter.mask}|${material.filter.group}`;
|
|
45
|
+
|
|
46
|
+
//#endregion
|
|
47
|
+
export { materialKey, resolveDefaults, resolveMaterial };
|
|
48
|
+
//# sourceMappingURL=material.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"material.js","names":[],"sources":["../../src/material.ts"],"sourcesContent":["import { type CollisionFilter, defaultFilter } from '@codexo/exojs-physics';\n\nimport type { ColliderDefaults, TileColliderContext } from './types';\n\nconst DEFAULT_FRICTION = 0.6;\nconst DEFAULT_RESTITUTION = 0;\nconst DEFAULT_DENSITY = 1;\n\n/** A fully resolved collider material: every field decided, nothing optional. */\nexport interface ResolvedMaterial {\n readonly friction: number;\n readonly restitution: number;\n readonly density: number;\n readonly isSensor: boolean;\n readonly filter: CollisionFilter;\n}\n\n/** Resolve the call-level defaults once, before any geometry is walked. */\nexport const resolveDefaults = (options: ColliderDefaults): ResolvedMaterial => ({\n friction: options.friction ?? DEFAULT_FRICTION,\n restitution: options.restitution ?? DEFAULT_RESTITUTION,\n density: options.density ?? DEFAULT_DENSITY,\n isSensor: options.isSensor ?? false,\n filter: {\n category: options.filter?.category ?? defaultFilter.category,\n mask: options.filter?.mask ?? defaultFilter.mask,\n group: options.filter?.group ?? defaultFilter.group,\n },\n});\n\n/** Apply a resolver's overrides over already-resolved defaults. */\nexport const resolveMaterial = (defaults: ResolvedMaterial, resolver: ColliderDefaults['material'], context: TileColliderContext): ResolvedMaterial => {\n const override = resolver?.(context);\n\n if (override === undefined || override === null) {\n return defaults;\n }\n\n return {\n friction: override.friction ?? defaults.friction,\n restitution: override.restitution ?? defaults.restitution,\n density: override.density ?? defaults.density,\n isSensor: override.isSensor ?? defaults.isSensor,\n filter: {\n category: override.filter?.category ?? defaults.filter.category,\n mask: override.filter?.mask ?? defaults.filter.mask,\n group: override.filter?.group ?? defaults.filter.group,\n },\n };\n};\n\n/**\n * Identity of everything a chain collider can carry, used to decide which solid\n * cells may be traced into a common outline.\n *\n * `density` is deliberately absent: a chain has no mass properties and the\n * bodies are static, so two regions differing only in density are\n * indistinguishable once built, and keying on it would split outlines for no\n * observable difference.\n */\nexport const materialKey = (material: ResolvedMaterial): string =>\n `${material.friction}|${material.restitution}|${material.isSensor ? 1 : 0}|${material.filter.category}|${material.filter.mask}|${material.filter.group}`;\n"],"mappings":";;;AAIA,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB;;AAYxB,MAAa,mBAAmB,aAAiD;CAC/E,UAAU,QAAQ,YAAY;CAC9B,aAAa,QAAQ,eAAe;CACpC,SAAS,QAAQ,WAAW;CAC5B,UAAU,QAAQ,YAAY;CAC9B,QAAQ;EACN,UAAU,QAAQ,QAAQ,YAAY,cAAc;EACpD,MAAM,QAAQ,QAAQ,QAAQ,cAAc;EAC5C,OAAO,QAAQ,QAAQ,SAAS,cAAc;CAChD;AACF;;AAGA,MAAa,mBAAmB,UAA4B,UAAwC,YAAmD;CACrJ,MAAM,WAAW,WAAW,OAAO;CAEnC,IAAI,aAAa,UAAa,aAAa,MACzC,OAAO;CAGT,OAAO;EACL,UAAU,SAAS,YAAY,SAAS;EACxC,aAAa,SAAS,eAAe,SAAS;EAC9C,SAAS,SAAS,WAAW,SAAS;EACtC,UAAU,SAAS,YAAY,SAAS;EACxC,QAAQ;GACN,UAAU,SAAS,QAAQ,YAAY,SAAS,OAAO;GACvD,MAAM,SAAS,QAAQ,QAAQ,SAAS,OAAO;GAC/C,OAAO,SAAS,QAAQ,SAAS,SAAS,OAAO;EACnD;CACF;AACF;;;;;;;;;;AAWA,MAAa,eAAe,aAC1B,GAAG,SAAS,SAAS,GAAG,SAAS,YAAY,GAAG,SAAS,WAAW,IAAI,EAAE,GAAG,SAAS,OAAO,SAAS,GAAG,SAAS,OAAO,KAAK,GAAG,SAAS,OAAO"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { PhysicsBody, type PhysicsWorld } from '@codexo/exojs-physics';
|
|
2
|
+
import type { ObjectLayer, TileMapObject } from '@codexo/exojs-tilemap';
|
|
3
|
+
import type { ColliderDefaults } from './types';
|
|
4
|
+
/** Options for {@link buildObjectLayerColliders}. */
|
|
5
|
+
export interface ObjectColliderOptions extends ColliderDefaults {
|
|
6
|
+
/** Drop an object before a body is built for it. Return `true` to keep it. */
|
|
7
|
+
accept?: (object: TileMapObject) => boolean;
|
|
8
|
+
}
|
|
9
|
+
/** One static body built from one object, paired with its source. */
|
|
10
|
+
export interface ObjectCollider {
|
|
11
|
+
readonly object: TileMapObject;
|
|
12
|
+
readonly body: PhysicsBody;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Build one static body per collision object in an object layer and add them to
|
|
16
|
+
* `world`.
|
|
17
|
+
*
|
|
18
|
+
* An object layer is static data with no residency, so this is a one-shot
|
|
19
|
+
* build with no lifecycle: the caller owns the returned bodies and destroys
|
|
20
|
+
* them through the world. Use {@link import('./TileColliderStreamer').TileColliderStreamer}
|
|
21
|
+
* for tile layers, whose chunks come and go.
|
|
22
|
+
*
|
|
23
|
+
* The layer's pixel offset is applied, so the colliders land where the layer is
|
|
24
|
+
* drawn. Objects with no collision geometry (points, tile and text objects) are
|
|
25
|
+
* skipped, as is any object the decomposition rejects - with a warning, not an
|
|
26
|
+
* exception.
|
|
27
|
+
*/
|
|
28
|
+
export declare const buildObjectLayerColliders: (world: PhysicsWorld, layer: ObjectLayer, options?: ObjectColliderOptions) => ObjectCollider[];
|
|
29
|
+
//# sourceMappingURL=objectLayer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"objectLayer.d.ts","sourceRoot":"","sources":["../../src/objectLayer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,KAAK,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAIxE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAEhD,qDAAqD;AACrD,MAAM,WAAW,qBAAsB,SAAQ,gBAAgB;IAC7D,8EAA8E;IAC9E,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,aAAa,KAAK,OAAO,CAAC;CAC7C;AAED,qEAAqE;AACrE,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC;IAC/B,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;CAC5B;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,yBAAyB,GAAI,OAAO,YAAY,EAAE,OAAO,WAAW,EAAE,UAAS,qBAA0B,KAAG,cAAc,EA0BtI,CAAC"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { resolveDefaults, resolveMaterial } from "./material.js";
|
|
2
|
+
import { collidersForGeometry, objectLabel } from "./buildColliders.js";
|
|
3
|
+
import { PhysicsBody } from "@codexo/exojs-physics";
|
|
4
|
+
|
|
5
|
+
//#region src/objectLayer.ts
|
|
6
|
+
/**
|
|
7
|
+
* Build one static body per collision object in an object layer and add them to
|
|
8
|
+
* `world`.
|
|
9
|
+
*
|
|
10
|
+
* An object layer is static data with no residency, so this is a one-shot
|
|
11
|
+
* build with no lifecycle: the caller owns the returned bodies and destroys
|
|
12
|
+
* them through the world. Use {@link import('./TileColliderStreamer').TileColliderStreamer}
|
|
13
|
+
* for tile layers, whose chunks come and go.
|
|
14
|
+
*
|
|
15
|
+
* The layer's pixel offset is applied, so the colliders land where the layer is
|
|
16
|
+
* drawn. Objects with no collision geometry (points, tile and text objects) are
|
|
17
|
+
* skipped, as is any object the decomposition rejects - with a warning, not an
|
|
18
|
+
* exception.
|
|
19
|
+
*/
|
|
20
|
+
const buildObjectLayerColliders = (world, layer, options = {}) => {
|
|
21
|
+
const defaults = resolveDefaults(options);
|
|
22
|
+
const accept = options.accept;
|
|
23
|
+
const built = [];
|
|
24
|
+
for (const object of layer.objects) {
|
|
25
|
+
if (accept !== void 0 && !accept(object)) continue;
|
|
26
|
+
const x = object.x + layer.offsetX;
|
|
27
|
+
const y = object.y + layer.offsetY;
|
|
28
|
+
const material = resolveMaterial(defaults, options.material, {
|
|
29
|
+
type: object.type,
|
|
30
|
+
object
|
|
31
|
+
});
|
|
32
|
+
const colliders = collidersForGeometry({
|
|
33
|
+
...object,
|
|
34
|
+
x,
|
|
35
|
+
y
|
|
36
|
+
}, material, x, y, objectLabel(object));
|
|
37
|
+
if (colliders.length === 0) continue;
|
|
38
|
+
built.push({
|
|
39
|
+
object,
|
|
40
|
+
body: world.add(new PhysicsBody({
|
|
41
|
+
type: "static",
|
|
42
|
+
position: {
|
|
43
|
+
x,
|
|
44
|
+
y
|
|
45
|
+
},
|
|
46
|
+
colliders
|
|
47
|
+
}))
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
return built;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
//#endregion
|
|
54
|
+
export { buildObjectLayerColliders };
|
|
55
|
+
//# sourceMappingURL=objectLayer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"objectLayer.js","names":[],"sources":["../../src/objectLayer.ts"],"sourcesContent":["import { PhysicsBody, type PhysicsWorld } from '@codexo/exojs-physics';\nimport type { ObjectLayer, TileMapObject } from '@codexo/exojs-tilemap';\n\nimport { collidersForGeometry, objectLabel } from './buildColliders';\nimport { resolveDefaults, resolveMaterial } from './material';\nimport type { ColliderDefaults } from './types';\n\n/** Options for {@link buildObjectLayerColliders}. */\nexport interface ObjectColliderOptions extends ColliderDefaults {\n /** Drop an object before a body is built for it. Return `true` to keep it. */\n accept?: (object: TileMapObject) => boolean;\n}\n\n/** One static body built from one object, paired with its source. */\nexport interface ObjectCollider {\n readonly object: TileMapObject;\n readonly body: PhysicsBody;\n}\n\n/**\n * Build one static body per collision object in an object layer and add them to\n * `world`.\n *\n * An object layer is static data with no residency, so this is a one-shot\n * build with no lifecycle: the caller owns the returned bodies and destroys\n * them through the world. Use {@link import('./TileColliderStreamer').TileColliderStreamer}\n * for tile layers, whose chunks come and go.\n *\n * The layer's pixel offset is applied, so the colliders land where the layer is\n * drawn. Objects with no collision geometry (points, tile and text objects) are\n * skipped, as is any object the decomposition rejects - with a warning, not an\n * exception.\n */\nexport const buildObjectLayerColliders = (world: PhysicsWorld, layer: ObjectLayer, options: ObjectColliderOptions = {}): ObjectCollider[] => {\n const defaults = resolveDefaults(options);\n const accept = options.accept;\n const built: ObjectCollider[] = [];\n\n for (const object of layer.objects) {\n if (accept !== undefined && !accept(object)) {\n continue;\n }\n\n const x = object.x + layer.offsetX;\n const y = object.y + layer.offsetY;\n const material = resolveMaterial(defaults, options.material, { type: object.type, object });\n const colliders = collidersForGeometry({ ...object, x, y }, material, x, y, objectLabel(object));\n\n if (colliders.length === 0) {\n continue;\n }\n\n built.push({\n object,\n body: world.add(new PhysicsBody({ type: 'static', position: { x, y }, colliders })),\n });\n }\n\n return built;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCA,MAAa,6BAA6B,OAAqB,OAAoB,UAAiC,CAAC,MAAwB;CAC3I,MAAM,WAAW,gBAAgB,OAAO;CACxC,MAAM,SAAS,QAAQ;CACvB,MAAM,QAA0B,CAAC;CAEjC,KAAK,MAAM,UAAU,MAAM,SAAS;EAClC,IAAI,WAAW,UAAa,CAAC,OAAO,MAAM,GACxC;EAGF,MAAM,IAAI,OAAO,IAAI,MAAM;EAC3B,MAAM,IAAI,OAAO,IAAI,MAAM;EAC3B,MAAM,WAAW,gBAAgB,UAAU,QAAQ,UAAU;GAAE,MAAM,OAAO;GAAM;EAAO,CAAC;EAC1F,MAAM,YAAY,qBAAqB;GAAE,GAAG;GAAQ;GAAG;EAAE,GAAG,UAAU,GAAG,GAAG,YAAY,MAAM,CAAC;EAE/F,IAAI,UAAU,WAAW,GACvB;EAGF,MAAM,KAAK;GACT;GACA,MAAM,MAAM,IAAI,IAAI,YAAY;IAAE,MAAM;IAAU,UAAU;KAAE;KAAG;IAAE;IAAG;GAAU,CAAC,CAAC;EACpF,CAAC;CACH;CAEA,OAAO;AACT"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { PointLike } from '@codexo/exojs';
|
|
2
|
+
/**
|
|
3
|
+
* Trace the boundary of a set of whole tile cells into closed loops of grid
|
|
4
|
+
* vertices.
|
|
5
|
+
*
|
|
6
|
+
* @param coordinates - Cell coordinates as `[tx, ty, tx, ty, ...]`. Duplicates
|
|
7
|
+
* are ignored.
|
|
8
|
+
* @returns One loop of grid vertices per boundary: the outer boundary of every
|
|
9
|
+
* 4-connected component plus one loop per enclosed hole. Collinear
|
|
10
|
+
* vertices are removed, so a straight run of 200 cells is two
|
|
11
|
+
* vertices. Loops carry no repeated closing vertex.
|
|
12
|
+
*/
|
|
13
|
+
export declare const traceCellOutlines: (coordinates: readonly number[]) => PointLike[][];
|
|
14
|
+
//# sourceMappingURL=outline.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"outline.d.ts","sourceRoot":"","sources":["../../src/outline.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAgK/C;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iBAAiB,GAAI,aAAa,SAAS,MAAM,EAAE,KAAG,SAAS,EAAE,EA0D7E,CAAC"}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
//#region src/outline.ts
|
|
2
|
+
/**
|
|
3
|
+
* Boundary extraction for a set of whole tile cells.
|
|
4
|
+
*
|
|
5
|
+
* Turns an occupancy set into closed loops of grid vertices, wound so that the
|
|
6
|
+
* physics convention (outward normal of the edge `v -> w` is `(wy - vy, vx - wx)`
|
|
7
|
+
* normalised) puts the solid side outside an island boundary and inside a hole
|
|
8
|
+
* boundary. In a +Y-down space that means an island loop has a positive
|
|
9
|
+
* shoelace area and a hole loop a negative one.
|
|
10
|
+
*/
|
|
11
|
+
/** `+X`, `+Y`, `-X`, `-Y`, in that index order. */
|
|
12
|
+
const STEP_X = [
|
|
13
|
+
1,
|
|
14
|
+
0,
|
|
15
|
+
-1,
|
|
16
|
+
0
|
|
17
|
+
];
|
|
18
|
+
const STEP_Y = [
|
|
19
|
+
0,
|
|
20
|
+
1,
|
|
21
|
+
0,
|
|
22
|
+
-1
|
|
23
|
+
];
|
|
24
|
+
/**
|
|
25
|
+
* Turn preference at a vertex where two loops touch, relative to the incoming
|
|
26
|
+
* direction: toward the solid side first, then straight, then away from it.
|
|
27
|
+
* Hugging the solid at every ambiguous corner is what separates two regions
|
|
28
|
+
* that meet diagonally into two correctly wound loops instead of one loop that
|
|
29
|
+
* crosses itself.
|
|
30
|
+
*/
|
|
31
|
+
const TURN_ORDER = [
|
|
32
|
+
1,
|
|
33
|
+
0,
|
|
34
|
+
3
|
|
35
|
+
];
|
|
36
|
+
const key = (x, y) => `${x},${y}`;
|
|
37
|
+
/**
|
|
38
|
+
* Split an occupancy set into 4-connected components. Cells that touch only at
|
|
39
|
+
* a corner are separate components: an 8-connected component would produce a
|
|
40
|
+
* boundary that pinches at the shared vertex, where the solid side is not
|
|
41
|
+
* defined.
|
|
42
|
+
*/
|
|
43
|
+
const components = (cells, coordinates) => {
|
|
44
|
+
const remaining = new Set(cells);
|
|
45
|
+
const result = [];
|
|
46
|
+
for (let i = 0; i < coordinates.length; i += 2) {
|
|
47
|
+
const startKey = key(coordinates[i], coordinates[i + 1]);
|
|
48
|
+
if (!remaining.has(startKey)) continue;
|
|
49
|
+
const component = /* @__PURE__ */ new Set();
|
|
50
|
+
const stack = [coordinates[i], coordinates[i + 1]];
|
|
51
|
+
remaining.delete(startKey);
|
|
52
|
+
component.add(startKey);
|
|
53
|
+
while (stack.length > 0) {
|
|
54
|
+
const y = stack.pop();
|
|
55
|
+
const x = stack.pop();
|
|
56
|
+
for (let direction = 0; direction < 4; direction++) {
|
|
57
|
+
const nx = x + STEP_X[direction];
|
|
58
|
+
const ny = y + STEP_Y[direction];
|
|
59
|
+
const neighbour = key(nx, ny);
|
|
60
|
+
if (!remaining.has(neighbour)) continue;
|
|
61
|
+
remaining.delete(neighbour);
|
|
62
|
+
component.add(neighbour);
|
|
63
|
+
stack.push(nx, ny);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
result.push(component);
|
|
67
|
+
}
|
|
68
|
+
return result;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* One directed unit edge per cell side that faces empty space, oriented so the
|
|
72
|
+
* solid stays on the same side of every edge.
|
|
73
|
+
*/
|
|
74
|
+
const boundaryEdges = (component) => {
|
|
75
|
+
const edges = /* @__PURE__ */ new Map();
|
|
76
|
+
const add = (x, y, direction) => {
|
|
77
|
+
const from = key(x, y);
|
|
78
|
+
let slots = edges.get(from);
|
|
79
|
+
if (slots === void 0) {
|
|
80
|
+
slots = [
|
|
81
|
+
false,
|
|
82
|
+
false,
|
|
83
|
+
false,
|
|
84
|
+
false
|
|
85
|
+
];
|
|
86
|
+
edges.set(from, slots);
|
|
87
|
+
}
|
|
88
|
+
slots[direction] = true;
|
|
89
|
+
};
|
|
90
|
+
for (const cell of component) {
|
|
91
|
+
const comma = cell.indexOf(",");
|
|
92
|
+
const x = Number(cell.slice(0, comma));
|
|
93
|
+
const y = Number(cell.slice(comma + 1));
|
|
94
|
+
if (!component.has(key(x, y - 1))) add(x, y, 0);
|
|
95
|
+
if (!component.has(key(x + 1, y))) add(x + 1, y, 1);
|
|
96
|
+
if (!component.has(key(x, y + 1))) add(x + 1, y + 1, 2);
|
|
97
|
+
if (!component.has(key(x - 1, y))) add(x, y + 1, 3);
|
|
98
|
+
}
|
|
99
|
+
return edges;
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Rotate a loop to start at its lowest `(x, y)` vertex. The walk starts wherever
|
|
103
|
+
* the first unused edge happens to be, which depends on the order the cells were
|
|
104
|
+
* handed in; a canonical start makes the emitted vertex array itself independent
|
|
105
|
+
* of that, not just the boundary it describes.
|
|
106
|
+
*/
|
|
107
|
+
const rotateToLowestVertex = (loop) => {
|
|
108
|
+
let start = 0;
|
|
109
|
+
for (let i = 2; i < loop.length; i += 2) {
|
|
110
|
+
const x = loop[i];
|
|
111
|
+
const y = loop[i + 1];
|
|
112
|
+
if (x < loop[start] || x === loop[start] && y < loop[start + 1]) start = i;
|
|
113
|
+
}
|
|
114
|
+
return [...loop.slice(start), ...loop.slice(0, start)];
|
|
115
|
+
};
|
|
116
|
+
/** Drop every vertex whose two adjacent edges point the same way. */
|
|
117
|
+
const dropCollinear = (loop) => {
|
|
118
|
+
const count = loop.length / 2;
|
|
119
|
+
const reduced = [];
|
|
120
|
+
for (let i = 0; i < count; i++) {
|
|
121
|
+
const previous = (i - 1 + count) % count;
|
|
122
|
+
const next = (i + 1) % count;
|
|
123
|
+
const inX = loop[i * 2] - loop[previous * 2];
|
|
124
|
+
const inY = loop[i * 2 + 1] - loop[previous * 2 + 1];
|
|
125
|
+
const outX = loop[next * 2] - loop[i * 2];
|
|
126
|
+
if (inX * (loop[next * 2 + 1] - loop[i * 2 + 1]) - inY * outX !== 0) reduced.push(loop[i * 2], loop[i * 2 + 1]);
|
|
127
|
+
}
|
|
128
|
+
return reduced;
|
|
129
|
+
};
|
|
130
|
+
/** Flat `[x, y, ...]` coordinates as points. */
|
|
131
|
+
const toPoints = (loop) => {
|
|
132
|
+
const points = [];
|
|
133
|
+
for (let i = 0; i < loop.length; i += 2) points.push({
|
|
134
|
+
x: loop[i],
|
|
135
|
+
y: loop[i + 1]
|
|
136
|
+
});
|
|
137
|
+
return points;
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* Trace the boundary of a set of whole tile cells into closed loops of grid
|
|
141
|
+
* vertices.
|
|
142
|
+
*
|
|
143
|
+
* @param coordinates - Cell coordinates as `[tx, ty, tx, ty, ...]`. Duplicates
|
|
144
|
+
* are ignored.
|
|
145
|
+
* @returns One loop of grid vertices per boundary: the outer boundary of every
|
|
146
|
+
* 4-connected component plus one loop per enclosed hole. Collinear
|
|
147
|
+
* vertices are removed, so a straight run of 200 cells is two
|
|
148
|
+
* vertices. Loops carry no repeated closing vertex.
|
|
149
|
+
*/
|
|
150
|
+
const traceCellOutlines = (coordinates) => {
|
|
151
|
+
const cells = /* @__PURE__ */ new Set();
|
|
152
|
+
for (let i = 0; i < coordinates.length; i += 2) cells.add(key(coordinates[i], coordinates[i + 1]));
|
|
153
|
+
const loops = [];
|
|
154
|
+
for (const component of components(cells, coordinates)) {
|
|
155
|
+
const edges = boundaryEdges(component);
|
|
156
|
+
for (const [startVertex, startSlots] of edges) for (let startDirection = 0; startDirection < 4; startDirection++) {
|
|
157
|
+
if (!startSlots[startDirection]) continue;
|
|
158
|
+
const comma = startVertex.indexOf(",");
|
|
159
|
+
const loop = [];
|
|
160
|
+
let x = Number(startVertex.slice(0, comma));
|
|
161
|
+
let y = Number(startVertex.slice(comma + 1));
|
|
162
|
+
let direction = startDirection;
|
|
163
|
+
for (;;) {
|
|
164
|
+
const slots = edges.get(key(x, y));
|
|
165
|
+
slots[direction] = false;
|
|
166
|
+
loop.push(x, y);
|
|
167
|
+
x += STEP_X[direction];
|
|
168
|
+
y += STEP_Y[direction];
|
|
169
|
+
const nextSlots = edges.get(key(x, y));
|
|
170
|
+
if (nextSlots === void 0) break;
|
|
171
|
+
let next = -1;
|
|
172
|
+
for (const turn of TURN_ORDER) {
|
|
173
|
+
const candidate = (direction + turn) % 4;
|
|
174
|
+
if (nextSlots[candidate]) {
|
|
175
|
+
next = candidate;
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (next === -1) break;
|
|
180
|
+
direction = next;
|
|
181
|
+
}
|
|
182
|
+
if (loop.length >= 6) loops.push(toPoints(rotateToLowestVertex(dropCollinear(loop))));
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return loops;
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
//#endregion
|
|
189
|
+
export { traceCellOutlines };
|
|
190
|
+
//# sourceMappingURL=outline.js.map
|