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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(spline): TerrainBand2D draws a 2D ground along a Spline, with a surface lip and an optional chain collider
yhh463d6f92faab
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex da2079a39..0f0f1b039 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: 115 public · 161 beta · 1983 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 1987 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -10678,6 +10678,28 @@ suspendAudio: () => voidComponentDef<TerrainData>```+## TerrainBand2D — const @experimental+```+ComponentDef<TerrainBand2DData>+```++## TerrainBand2DData — interface @experimental+```+collider: boolean+depth: number+edgeColor: { r: number; g: number; b: number; a: number; }+edgeWidth: number+resolution: number+tile: number+```++## TerrainBandBuild — interface @experimental+```+closed: boolean+geometry: MeshRendererGeometry+outline: Vec2[]+```+## TerrainData — interface @experimental```cellSize: number@@ -13635,6 +13657,11 @@ MotionDriver<AnimatorBlend2DMotion>(points: readonly Vec2[], style: PathStyle): MeshRendererGeometry```+## buildTerrainBand — function @experimental+```+(points: readonly SplinePoint[], closedCurve: boolean, band: TerrainBand2DData): TerrainBandBuild | null+```+## buildText — function @experimental```(init?: TextInit): TextDatadiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex d5ef1d837..299ea2f3e 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 166 beta · 2002 experimental · 3 deprecated+Symbols: 115 public · 166 beta · 2006 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -10891,6 +10891,28 @@ suspendAudio: () => voidComponentDef<TerrainData>```+## TerrainBand2D — const @experimental+```+ComponentDef<TerrainBand2DData>+```++## TerrainBand2DData — interface @experimental+```+collider: boolean+depth: number+edgeColor: { r: number; g: number; b: number; a: number; }+edgeWidth: number+resolution: number+tile: number+```++## TerrainBandBuild — interface @experimental+```+closed: boolean+geometry: MeshRendererGeometry+outline: Vec2[]+```+## TerrainData — interface @experimental```cellSize: number@@ -13863,6 +13885,11 @@ MotionDriver<AnimatorBlend2DMotion>(points: readonly Vec2[], style: PathStyle): MeshRendererGeometry```+## buildTerrainBand — function @experimental+```+(points: readonly SplinePoint[], closedCurve: boolean, band: TerrainBand2DData): TerrainBandBuild | null+```+## buildText — function @experimental```(init?: TextInit): TextDatadiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 542228784..00058cdba 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: 115 public · 163 beta · 1982 experimental · 3 deprecated+Symbols: 115 public · 163 beta · 1986 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -10673,6 +10673,28 @@ suspendAudio: () => voidComponentDef<TerrainData>```+## TerrainBand2D — const @experimental+```+ComponentDef<TerrainBand2DData>+```++## TerrainBand2DData — interface @experimental+```+collider: boolean+depth: number+edgeColor: { r: number; g: number; b: number; a: number; }+edgeWidth: number+resolution: number+tile: number+```++## TerrainBandBuild — interface @experimental+```+closed: boolean+geometry: MeshRendererGeometry+outline: Vec2[]+```+## TerrainData — interface @experimental```cellSize: number@@ -13630,6 +13652,11 @@ MotionDriver<AnimatorBlend2DMotion>(points: readonly Vec2[], style: PathStyle): MeshRendererGeometry```+## buildTerrainBand — function @experimental+```+(points: readonly SplinePoint[], closedCurve: boolean, band: TerrainBand2DData): TerrainBandBuild | null+```+## buildText — function @experimental```(init?: TextInit): TextDatadiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 8838dca4e..9f8da8044 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 161 beta · 2004 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 2008 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -10968,6 +10968,28 @@ suspendAudio: () => voidComponentDef<TerrainData>```+## TerrainBand2D — const @experimental+```+ComponentDef<TerrainBand2DData>+```++## TerrainBand2DData — interface @experimental+```+collider: boolean+depth: number+edgeColor: { r: number; g: number; b: number; a: number; }+edgeWidth: number+resolution: number+tile: number+```++## TerrainBandBuild — interface @experimental+```+closed: boolean+geometry: MeshRendererGeometry+outline: Vec2[]+```+## TerrainData — interface @experimental```cellSize: number@@ -13931,6 +13953,11 @@ MotionDriver<AnimatorBlend2DMotion>(points: readonly Vec2[], style: PathStyle): MeshRendererGeometry```+## buildTerrainBand — function @experimental+```+(points: readonly SplinePoint[], closedCurve: boolean, band: TerrainBand2DData): TerrainBandBuild | null+```+## buildText — function @experimental```(init?: TextInit): TextDatadiff --git a/sdk/etc/spline.api.md b/sdk/etc/spline.api.mdindex 4b9028193..3f15033db 100644--- a/sdk/etc/spline.api.md+++ b/sdk/etc/spline.api.md@@ -1,7 +1,7 @@# API surface — esengine/spline<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 0 beta · 12 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 16 experimental · 0 deprecated## PathFollower — const @experimental```@@ -75,6 +75,33 @@ y: numberz: number```+## TerrainBand2D — const @experimental+```+ComponentDef<TerrainBand2DData>+```++## TerrainBand2DData — interface @experimental+```+collider: boolean+depth: number+edgeColor: { r: number; g: number; b: number; a: number; }+edgeWidth: number+resolution: number+tile: number+```++## TerrainBandBuild — interface @experimental+```+closed: boolean+geometry: MeshRendererGeometry+outline: Vec2[]+```++## buildTerrainBand — function @experimental+```+(points: readonly SplinePoint[], closedCurve: boolean, band: TerrainBand2DData): TerrainBandBuild | null+```+## pathPlace — function @experimental```(travelled: number, length: number, mode: number, forward?: boolean): { s: number; done: boolean; }diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex b94d19126..96bbe7bed 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 161 beta · 1995 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 1999 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -10680,6 +10680,28 @@ suspendAudio: () => voidComponentDef<TerrainData>```+## TerrainBand2D — const @experimental+```+ComponentDef<TerrainBand2DData>+```++## TerrainBand2DData — interface @experimental+```+collider: boolean+depth: number+edgeColor: { r: number; g: number; b: number; a: number; }+edgeWidth: number+resolution: number+tile: number+```++## TerrainBandBuild — interface @experimental+```+closed: boolean+geometry: MeshRendererGeometry+outline: Vec2[]+```+## TerrainData — interface @experimental```cellSize: number@@ -13662,6 +13684,11 @@ MotionDriver<AnimatorBlend2DMotion>(points: readonly Vec2[], style: PathStyle): MeshRendererGeometry```+## buildTerrainBand — function @experimental+```+(points: readonly SplinePoint[], closedCurve: boolean, band: TerrainBand2DData): TerrainBandBuild | null+```+## buildText — function @experimental```(init?: TextInit): TextDatadiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 056d29180..4de78b580 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -826,6 +826,7 @@ export { PlacementDiffs, type PlacementChange, type PlacementDiffsData } from '.export { Bakes, BakesRes, bakesOf, finish, type WorkJob, type BakeProgress } from './runtime/bakes';export { CollisionGeometry, CollisionGeometryRes, collisionGeometryOf, type CollisionPiece } from './runtime/collisionGeometry';export { Spline, SplinePlugin, splinePlugin, PathFollower, PathMode, PathOrient, pathPlace, type SplineData, type PathFollowerData } from './spline/splinePlugin';+export { TerrainBand2D, buildTerrainBand, type TerrainBand2DData, type TerrainBandBuild } from './spline/terrainBand2D';export { SplineCurve, type SplinePoint, type SplineNearest } from './spline/curve';export {WaterBody, WaterForm, Waters, WatersRes, WaterPlugin, waterPlugin, type WaterBodyData, type WaterSample,diff --git a/sdk/src/render/vectorPath.ts b/sdk/src/render/vectorPath.tsindex 83e4ba02b..5fc56f214 100644--- a/sdk/src/render/vectorPath.ts+++ b/sdk/src/render/vectorPath.ts@@ -498,3 +498,15 @@ export function circlePoints(cx: number, cy: number, radius: number, segments =}return out;}++/**+ * The triangles (indices into `ring`) that cover a simple polygon, whichever way round it is given.+ * @experimental+ */+export function triangulateRing(ring: readonly Vec2[]): number[] {+ if (ring.length < 3) return [];+ if (signedArea(ring) >= 0) return earClip(ring);+ // Clockwise: clip the reverse and map the indices back.+ const n = ring.length;+ return earClip(ring.slice().reverse()).map((i) => n - 1 - i);+}diff --git a/sdk/src/spline/index.ts b/sdk/src/spline/index.tsindex 4416db67d..65085ce42 100644--- a/sdk/src/spline/index.ts+++ b/sdk/src/spline/index.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamexport { Spline, SplinePlugin, splinePlugin, PathFollower, PathMode, PathOrient, pathPlace, type SplineData, type PathFollowerData } from './splinePlugin';+export { TerrainBand2D, buildTerrainBand, type TerrainBand2DData, type TerrainBandBuild } from './terrainBand2D';export { SplineCurve, type SplinePoint, type SplineNearest } from './curve';// Importing this subpath INSTALLS splines — see tilemap/index.ts.diff --git a/sdk/src/spline/splinePlugin.ts b/sdk/src/spline/splinePlugin.tsindex 3be252a21..c20a98553 100644--- a/sdk/src/spline/splinePlugin.ts+++ b/sdk/src/spline/splinePlugin.ts@@ -14,6 +14,7 @@ import { Res, Time, type TimeData } from '../ecs/resource';import { playModeOnly } from '../ecs/env';import { defineComponent, Transform, type ComponentDef, type TransformData } from '../ecs/component';import { SplineCurve, type SplinePoint } from './curve';+import { installTerrainBands } from './terrainBand2D';/** The fields of the `Spline` component. @experimental */export interface SplineData {@@ -118,6 +119,7 @@ export class SplinePlugin implements Plugin {app.addSystemToSchedule(Schedule.Update,defineSystem([Res(Time)], (time: TimeData) => this.follow(app, time.delta), { name: 'PathFollowerSystem' }),{ runIf: playModeOnly });+ installTerrainBands(app);}private curveOf(app: App, entity: number): { curve: SplineCurve; at: TransformData } | null {diff --git a/sdk/src/spline/terrainBand2D.ts b/sdk/src/spline/terrainBand2D.tsnew file mode 100644index 000000000..e772bb837--- /dev/null+++ b/sdk/src/spline/terrainBand2D.ts@@ -0,0 +1,185 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file terrainBand2D.ts+ * @brief A 2D ground drawn along a Spline: a filled body, a lip along its surface, and the chain collider that stands on it.+ *+ * @details An open spline is a ground profile: the fill reaches from the curve down to `depth` below its lowest point, and the lip runs along+ * the curve. A closed one is a shape (an island, a platform): the fill is what it encloses and the lip runs round the inside of+ * its rim. Either way the curve is read in the entity's own x, y, the way a sprite is, so moving the entity moves the ground.+ *+ * The mesh is the entity's own MeshRenderer geometry (so it sorts, batches and saves like any other, and the renderer's texture+ * and tint apply), rebuilt only when the spline or the band's fields change. The fill's texture coordinates are in world units+ * over `tile`, so a texture repeats at one size however the curve is drawn.+ */+import type { App } from '../app/app';+import type { Entity, Vec2 } from '../types';+import { defineSystem, Schedule } from '../ecs/system';+import { defineComponent, MeshRenderer, Canvas, type ComponentDef, type MeshRendererGeometry } from '../ecs/component';+import { MeshRenderers } from '../render/meshRenderer';+import { triangulateRing } from '../render/vectorPath';+import { ChainCollider2D, type ChainCollider2DData } from '../physics/PhysicsComponents';+import { SplineCurve, type SplinePoint } from './curve';+import { Spline, type SplineData } from './splinePlugin';++/** The fields of the `TerrainBand2D` component. @experimental */+export interface TerrainBand2DData {+ /** How far apart, along the curve, the points of the outline are: smaller is smoother and costs more triangles. */+ resolution: number;+ /** An open spline's fill reaches this far below its lowest point. A closed one ignores it. */+ depth: number;+ /** The length of one repeat of the fill's texture, in world units. */+ tile: number;+ /** How wide the lip along the surface is, drawn over the fill; 0 draws none. */+ edgeWidth: number;+ /** The lip's colour, multiplying the texture under it. */+ edgeColor: { r: number; g: number; b: number; a: number };+ /** Whether the band gives its entity a chain collider along the surface, for a static body to carry. */+ collider: boolean;+}++/**+ * Ground along the `Spline` of the same entity, drawn by the entity's MeshRenderer.+ *+ * @experimental+ */+export const TerrainBand2D: ComponentDef<TerrainBand2DData> = defineComponent<TerrainBand2DData>('TerrainBand2D', {+ resolution: 16, depth: 200, tile: 128, edgeWidth: 12, edgeColor: { r: 0.35, g: 0.65, b: 0.2, a: 1 }, collider: false,+}, {+ fields: {+ resolution: { min: 1, category: 'Shape', tooltip: 'How far apart, along the curve, the outline\'s points are. Smaller is smoother and costs more triangles.' },+ depth: { min: 0, category: 'Shape', tooltip: 'How far below its lowest point an open spline\'s fill reaches. A closed spline ignores it.' },+ tile: { min: 1, category: 'Look', tooltip: 'The length of one repeat of the fill\'s texture, in world units.' },+ edgeWidth: { min: 0, category: 'Look', tooltip: 'How wide the lip along the surface is, drawn over the fill. 0 draws none.' },+ edgeColor: { category: 'Look', tooltip: 'The lip\'s colour, multiplying the texture under it.' },+ collider: { category: 'Collision', tooltip: 'Give this entity a chain collider along the surface. Add a static Rigidbody2D to make it solid.' },+ },+});++/** What a band is built into: the mesh, and the outline its collider follows. */+export interface TerrainBandBuild {+ geometry: MeshRendererGeometry;+ /** The surface, in the entity's own space: the curve for an open spline, the ring for a closed one. */+ outline: Vec2[];+ closed: boolean;+}++const lerpColor = (c: TerrainBand2DData['edgeColor']): number[] => [c.r, c.g, c.b, c.a];++/** The points of the curve, a `step` apart. An open curve ends on its last point; a closed one is a ring with no repeat. */+function sampleCurve(curve: SplineCurve, step: number): Vec2[] {+ const n = Math.max(curve.closed ? 3 : 2, Math.ceil(curve.length / Math.max(step, 1e-3)) + (curve.closed ? 0 : 1));+ const out: Vec2[] = [];+ const last = curve.closed ? n : n - 1;+ for (let i = 0; i < n; i++) {+ const p = curve.position((i / last) * curve.length);+ out.push({ x: p[0], y: p[1] });+ }+ return out;+}++const area = (ring: readonly Vec2[]): number => {+ let a = 0;+ for (let i = 0; i < ring.length; i++) { const p = ring[i]!, q = ring[(i + 1) % ring.length]!; a += p.x * q.y - q.x * p.y; }+ return a / 2;+};++/**+ * The geometry of a band over `points`. Pure: the same inputs give the same mesh.+ *+ * @experimental+ */+export function buildTerrainBand(points: readonly SplinePoint[], closedCurve: boolean, band: TerrainBand2DData): TerrainBandBuild | null {+ if (points.length < 2) return null;+ const curve = new SplineCurve(points, closedCurve);+ let outline = sampleCurve(curve, band.resolution);+ const closed = curve.closed;+ // A closed ring goes counter-clockwise (its surface faces out to the right of travel); an open profile goes left to right.+ if (closed ? area(outline) < 0 : outline[outline.length - 1]!.x < outline[0]!.x) outline = outline.slice().reverse();++ const fill: Vec2[] = closed ? outline : (() => {+ const bottom = Math.min(...outline.map((p) => p.y)) - Math.max(band.depth, 0);+ return [...outline, { x: outline[outline.length - 1]!.x, y: bottom }, { x: outline[0]!.x, y: bottom }];+ })();++ const positions: number[] = [], uvs: number[] = [], colors: number[] = [], indices: number[] = [];+ const tile = Math.max(band.tile, 1e-3);+ const push = (x: number, y: number, c: number[]): number => {+ positions.push(x, y); uvs.push(x / tile, y / tile); colors.push(c[0]!, c[1]!, c[2]!, c[3]!);+ return positions.length / 2 - 1;+ };+ const white = [1, 1, 1, 1];+ for (const p of fill) push(p.x, p.y, white);+ for (const i of triangulateRing(fill)) indices.push(i);++ // The lip: a strip from each surface point a lip's width into the fill, along the outline's surface side.+ if (band.edgeWidth > 0) {+ const n = outline.length;+ const edge = lerpColor(band.edgeColor);+ const inward: Vec2[] = [];+ for (let i = 0; i < n; i++) {+ const a = outline[closed ? (i + n - 1) % n : Math.max(i - 1, 0)]!;+ const c = outline[closed ? (i + 1) % n : Math.min(i + 1, n - 1)]!;+ const dx = c.x - a.x, dy = c.y - a.y, len = Math.hypot(dx, dy) || 1;+ // Into the fill is to the left of travel round a counter-clockwise ring; for an open profile (left to right) it is down, to the right.+ inward.push(closed ? { x: -dy / len, y: dx / len } : { x: dy / len, y: -dx / len });+ }+ const top: number[] = [], under: number[] = [];+ for (let i = 0; i < n; i++) {+ const p = outline[i]!, d = inward[i]!;+ top.push(push(p.x, p.y, edge));+ under.push(push(p.x + d.x * band.edgeWidth, p.y + d.y * band.edgeWidth, edge));+ }+ const pieces = closed ? n : n - 1;+ for (let i = 0; i < pieces; i++) {+ const j = (i + 1) % n;+ // Counter-clockwise, so it faces the same way as the fill.+ if (closed) indices.push(top[i]!, under[i]!, under[j]!, top[i]!, under[j]!, top[j]!);+ else indices.push(top[i]!, under[j]!, top[j]!, top[i]!, under[i]!, under[j]!);+ }+ }+ return { geometry: { positions, uvs, colors, indices }, outline, closed };+}++/** The pixels-per-unit physics measures a Transform's units in. */+function pixelsPerUnit(app: App): number {+ for (const entity of app.world.getEntitiesWithComponents([Canvas])) {+ const ppu = (app.world.get(entity, Canvas) as { pixelsPerUnit?: number }).pixelsPerUnit;+ if (ppu) return ppu;+ }+ return 100;+}++/** Keeps every `TerrainBand2D`'s mesh and collider matching its spline. Called once by the spline plugin. */+export function installTerrainBands(app: App): void {+ const built = new Map<Entity, string>();+ const wroteCollider = new Set<Entity>();+ app.world.onDespawn((entity: Entity) => { built.delete(entity); wroteCollider.delete(entity); });++ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => {+ const world = app.world;+ if (!app.hasResource(MeshRenderers)) return;+ const api = app.getResource(MeshRenderers);+ for (const entity of world.getEntitiesWithComponents([TerrainBand2D, Spline])) {+ const band = world.get(entity, TerrainBand2D) as TerrainBand2DData;+ const spline = world.get(entity, Spline) as SplineData;+ const ppu = band.collider ? pixelsPerUnit(app) : 0;+ const key = JSON.stringify([spline.points, spline.closed, band, ppu]);+ if (built.get(entity) === key) continue;+ built.set(entity, key);+ const result = buildTerrainBand(spline.points, spline.closed, band);+ if (!world.has(entity, MeshRenderer)) world.insert(entity, MeshRenderer, { enabled: true });+ if (result) api.setGeometry(entity, result.geometry); else api.clearGeometry(entity);+ if (band.collider && result && result.outline.length >= 4) {+ // Physics measures in units, the Transform in pixels.+ const points = result.outline.map((p) => ({ x: p.x / ppu, y: p.y / ppu }));+ const held = world.has(entity, ChainCollider2D) ? world.get(entity, ChainCollider2D) as ChainCollider2DData : {};+ world.insert(entity, ChainCollider2D, { ...held, points, isLoop: result.closed });+ wroteCollider.add(entity);+ } else if (wroteCollider.has(entity)) {+ world.remove(entity, ChainCollider2D);+ wroteCollider.delete(entity);+ }+ }+ }, { name: 'TerrainBand2DSystem' }));+}diff --git a/sdk/tests/terrain-band-2d.test.ts b/sdk/tests/terrain-band-2d.test.tsnew file mode 100644index 000000000..5ef761049--- /dev/null+++ b/sdk/tests/terrain-band-2d.test.ts@@ -0,0 +1,148 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';+import { World } from '../src/ecs/world';+import { Transform, MeshRenderer } from '../src/ecs/component';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import { ChainCollider2D } from '../src/physics/PhysicsComponents';+import { MeshRenderers } from '../src/render/meshRenderer';+import { Spline } from '../src/spline/splinePlugin';+import { TerrainBand2D, buildTerrainBand, installTerrainBands, type TerrainBand2DData } from '../src/spline/terrainBand2D';+import { triangulateRing } from '../src/render/vectorPath';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';++const band = (over: Partial<TerrainBand2DData> = {}): TerrainBand2DData => ({+ resolution: 50, depth: 50, tile: 100, edgeWidth: 0, edgeColor: { r: 0, g: 1, b: 0, a: 1 }, collider: false, ...over,+});+const pt = (x: number, y: number) => ({ x, y, z: 0, width: 1 });++/** The summed area of the triangles of a geometry, from `from` to `to` indices. */+function coverage(g: { positions: number[]; indices: number[] }, from = 0, to = g.indices.length): number {+ let a = 0;+ for (let i = from; i < to; i += 3) {+ const [p, q, r] = [g.indices[i]!, g.indices[i + 1]!, g.indices[i + 2]!];+ const ax = g.positions[p * 2]!, ay = g.positions[p * 2 + 1]!;+ a += Math.abs((g.positions[q * 2]! - ax) * (g.positions[r * 2 + 1]! - ay) - (g.positions[r * 2]! - ax) * (g.positions[q * 2 + 1]! - ay)) / 2;+ }+ return a;+}++describe('triangulateRing', () => {+ it('covers a square the same way round either way', () => {+ const ring = [{ x: 0, y: 0 }, { x: 10, y: 0 }, { x: 10, y: 10 }, { x: 0, y: 10 }];+ const g = (r: typeof ring) => ({ positions: r.flatMap((p) => [p.x, p.y]), indices: triangulateRing(r) });+ expect(coverage(g(ring))).toBeCloseTo(100);+ expect(coverage(g(ring.slice().reverse()))).toBeCloseTo(100);+ });+});++describe('buildTerrainBand', () => {+ it('fills an open profile from its curve down to the depth', () => {+ const b = buildTerrainBand([pt(0, 0), pt(100, 0)], false, band())!;+ // 100 wide, 50 deep.+ expect(coverage(b.geometry)).toBeCloseTo(5000, 0);+ expect(b.closed).toBe(false);+ expect(b.outline[0]).toEqual({ x: 0, y: 0 });+ expect(b.outline[b.outline.length - 1]!.x).toBeCloseTo(100);+ });++ it('goes left to right whichever way the profile was drawn', () => {+ const a = buildTerrainBand([pt(0, 0), pt(100, 0)], false, band())!;+ const r = buildTerrainBand([pt(100, 0), pt(0, 0)], false, band())!;+ expect(coverage(r.geometry)).toBeCloseTo(coverage(a.geometry), 0);+ expect(r.outline[0]!.x).toBeCloseTo(0);+ });++ it('fills what a closed spline encloses, wound either way', () => {+ const square = [pt(0, 0), pt(100, 0), pt(100, 100), pt(0, 100)];+ const b = buildTerrainBand(square, true, band({ resolution: 10 }))!;+ expect(b.closed).toBe(true);+ // The triangles cover exactly the ring the curve was cut into (the curve bulges past the square's corners, so not the square's 10000).+ let ring = 0;+ for (let i = 0; i < b.outline.length; i++) { const a = b.outline[i]!, c = b.outline[(i + 1) % b.outline.length]!; ring += a.x * c.y - c.x * a.y; }+ expect(coverage(b.geometry)).toBeCloseTo(Math.abs(ring) / 2, 0);+ expect(coverage(b.geometry)).toBeGreaterThan(10000);+ const flipped = buildTerrainBand(square.slice().reverse(), true, band({ resolution: 10 }))!;+ expect(coverage(flipped.geometry)).toBeCloseTo(coverage(b.geometry), 0);+ });++ it('draws a lip only when it has a width, under the surface and over the fill', () => {+ const none = buildTerrainBand([pt(0, 0), pt(100, 0)], false, band())!;+ const lip = buildTerrainBand([pt(0, 0), pt(100, 0)], false, band({ edgeWidth: 10 }))!;+ expect(lip.geometry.indices.length).toBeGreaterThan(none.geometry.indices.length);+ // The fill's triangles come first, then the lip's: 100 x 10 of them, on the fill side of the curve (below it).+ const fillIndices = none.geometry.indices.length;+ expect(coverage(lip.geometry, fillIndices)).toBeCloseTo(1000, 0);+ const edgeVertices = lip.geometry.positions.slice(none.geometry.positions.length);+ for (let i = 1; i < edgeVertices.length; i += 2) {+ expect(edgeVertices[i]!).toBeLessThanOrEqual(1e-6);+ expect(edgeVertices[i]!).toBeGreaterThanOrEqual(-10 - 1e-6);+ }+ // The lip is the lip's colour, the fill is white.+ expect(lip.geometry.colors!.slice(0, 4)).toEqual([1, 1, 1, 1]);+ expect(lip.geometry.colors!.slice(none.geometry.positions.length / 2 * 4, none.geometry.positions.length / 2 * 4 + 4)).toEqual([0, 1, 0, 1]);+ });++ it('lays the fill\'s texture in world units, so it repeats at one size', () => {+ const b = buildTerrainBand([pt(0, 0), pt(200, 0)], false, band({ tile: 100 }))!;+ const last = b.outline.length - 1;+ expect(b.geometry.uvs![last * 2]).toBeCloseTo(2);+ });++ it('builds nothing from one point', () => {+ expect(buildTerrainBand([pt(0, 0)], false, band())).toBeNull();+ });+});++describe.skipIf(!HAS_WASM)('TerrainBand2D system', () => {+ let engine: ESEngineModule, registry: CppRegistry, world: World;+ beforeAll(async () => { engine = await loadWasmModule(); });+ beforeEach(() => { registry = new engine.Registry(); world = new World(); world.connectCpp(registry, engine); });+ afterEach(() => { for (const e of world.getAllEntities()) world.despawn(e); world.disconnectCpp(); registry.delete(); });++ function install() {+ const uploads: number[] = [];+ const api = { setGeometry: (e: number) => { uploads.push(e); }, clearGeometry: () => {} };+ let system: { _fn: () => void } | null = null;+ const app = {+ world,+ hasResource: (r: unknown) => r === MeshRenderers,+ getResource: () => api,+ addSystemToSchedule: (_s: unknown, def: { _fn: () => void }) => { system = def; },+ };+ installTerrainBands(app as never);+ return { run: () => system!._fn(), uploads };+ }++ function ground(over: Partial<TerrainBand2DData> = {}) {+ const e = world.spawn();+ world.insert(e, Transform);+ world.insert(e, Spline, { points: [pt(0, 0), pt(100, 0), pt(200, 0), pt(300, 0)], closed: false });+ world.insert(e, TerrainBand2D, band(over));+ return e;+ }++ it('gives the entity a MeshRenderer and uploads its mesh once, until something changes', () => {+ const { run, uploads } = install();+ const e = ground();+ run(); run();+ expect(world.has(e, MeshRenderer)).toBe(true);+ expect(uploads).toEqual([e]);+ world.insert(e, TerrainBand2D, band({ edgeWidth: 8 }));+ run();+ expect(uploads).toEqual([e, e]);+ });++ it('writes a chain collider along the surface in physics units, and takes it back', () => {+ const { run } = install();+ const e = ground({ collider: true });+ run();+ const chain = world.get(e, ChainCollider2D);+ expect(chain.isLoop).toBe(false);+ // 100 pixels to the unit by default.+ expect(chain.points[chain.points.length - 1]!.x).toBeCloseTo(3);+ world.insert(e, TerrainBand2D, band({ collider: false }));+ run();+ expect(world.has(e, ChainCollider2D)).toBe(false);+ });+});