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(gameplay): grid snapping and a placement check, and the entities nearest a point
yhh62790b4c4331
diff --git a/docs/astro/src/content/docs/gameplay/markers.mdx b/docs/astro/src/content/docs/gameplay/markers.mdxindex c98325684..3a488a31f 100644--- a/docs/astro/src/content/docs/gameplay/markers.mdx+++ b/docs/astro/src/content/docs/gameplay/markers.mdx@@ -148,6 +148,21 @@ load, so they exist in play mode only; hand-authored Markers are ordinary serialentities.) The raw object-group data is still available through `getTilemapSource`if you need a shape's exact vertices.+## Finding what is nearest++An "interact" button needs one fact before it decides what it does: what stands near the player, and how near. `nearestMarkers(world, from, options)` answers it, nearest first:++```typescript+import { nearestMarkers, nearestEntities } from 'esengine/gameplay';++const near = nearestMarkers(world, { x: player.x, y: player.y }, { radius: 60, type: ['door', 'tree', 'bed'], limit: 1 });+if (near[0]) promptFor(world.get(near[0].entity, Marker).type); // what the button says is the game's+```++`type` takes one type or several, `has` keeps only markers whose `properties` carry every given key and value, `radius` and `limit` bound the answer, and `plane: 'xz'` measures on the ground.+`nearestEntities(world, Component, from, options)` is the same over any component, with a `filter` on its data. An entity switched off with `Disabled` is not found. It is one pass over+the entities that carry the component each time it is asked, which a button press or a prompt refreshed once a frame affords over the hundreds of things a village holds.+## Best practices- **Type by role, detail by properties.** A small, stable set of `type` values thediff --git a/docs/astro/src/content/docs/gameplay/physics.mdx b/docs/astro/src/content/docs/gameplay/physics.mdxindex 0813a894e..5ffc015b3 100644--- a/docs/astro/src/content/docs/gameplay/physics.mdx+++ b/docs/astro/src/content/docs/gameplay/physics.mdx@@ -250,6 +250,32 @@ Casts return `RaycastHit`s (`ShapeCastHit` is the same shape):| `normal` | `Vec2` | Surface normal at the hit point (unit vector). || `fraction` | number | Fraction of the cast distance at the hit, `0..1` — results sort by it, nearest first. |+## Placing on a grid++A build mode asks three things while a finger drags something over the ground, and `esengine/gameplay` answers them as plain functions (no component, no system): where does the thing sit+snapped to the grid, and may it stand there. What follows the finger (a ghost sprite), how it is tinted, and what a confirmed placement does are yours.++```typescript+import { snapFootprint, checkPlacement, type PlacementGrid } from 'esengine/gameplay';++const grid: PlacementGrid = { cellWidth: 32, cellHeight: 32 }; // originX / originY if cell (0, 0) is not at the world origin+const spot = snapFootprint(grid, fingerX, fingerY, 3, 1); // a 3 by 1 wall, centred on its middle cell+ghost.position.x = spot.x; ghost.position.y = spot.y; // the ghost sits on whole cells++const check = checkPlacement(grid, spot, {+ physics, // the Physics2D resource: any collider in the footprint is in the way+ mask: SOLID_LAYERS,+ solidAt: (x, y) => isTileSolid(layer, ...), // a solid tile under it blocks (see the tilemap guide)+ blocked: (col, row) => buildings.has(col, row), // your own table of what is taken+ ignore: new Set([ghostEntity]),+});+ghostSprite.color = check.clear ? GREEN : RED; // check.blockers and check.blockedCells say what is in the way+```++`snapToGrid` snaps a point to a cell middle or a cell corner; `gridCellAt` and `gridCellCentre` convert between cells and the world. An odd footprint centres on a cell and an even one on a corner,+each way on its own. Every probe is optional: one you do not pass blocks nothing. `solidAt` is sampled on a lattice over each cell (every `solidStep`, a quarter of a cell by default), so a solid tile+narrower than that can slip between the points; the physics query is asked once with the footprint shrunk a hair, so a wall that only touches its edge is not in the way.+## Collision & sensor eventsThe `Physics2DEvents` resource carries this frame's contacts. Set `isSensor: true` on adiff --git a/docs/astro/src/content/docs/zh-cn/gameplay/markers.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/markers.mdxindex cf09aee47..7e105d42d 100644--- a/docs/astro/src/content/docs/zh-cn/gameplay/markers.mdx+++ b/docs/astro/src/content/docs/zh-cn/gameplay/markers.mdx@@ -134,6 +134,19 @@ const onTrigger = defineSystem([Res(Physics2DEvents), Query(Marker)], (events, m(导入的对象在每次加载时从 `.tmj` 重新派生,因此只在播放模式存在;手工创建的 Marker 是普通的序列化实体。)如果你需要某个形状的精确顶点,原始的对象组数据仍可经 `getTilemapSource` 取得。+## 找出离得最近的++"交互"按钮在决定做什么之前要先知道一件事:玩家附近有什么、离多远。`nearestMarkers(world, from, options)` 回答它,按距离从近到远:++```typescript+import { nearestMarkers, nearestEntities } from 'esengine/gameplay';++const near = nearestMarkers(world, { x: player.x, y: player.y }, { radius: 60, type: ['door', 'tree', 'bed'], limit: 1 });+if (near[0]) promptFor(world.get(near[0].entity, Marker).type); // 按钮上写什么,由游戏决定+```++`type` 可以给一个或多个类型,`has` 只保留 `properties` 里带有全部给定键值的标记,`radius` 和 `limit` 限定结果范围,`plane: 'xz'` 表示在地面上量距离。`nearestEntities(world, Component, from, options)` 对任何组件都一样,并可用 `filter` 按组件数据过滤。被 `Disabled` 关掉的实体找不到。每次询问都是对带该组件的实体过一遍,按一次按钮,或每帧刷新一次提示,在一个村子里几百个东西的规模下完全负担得起。+## 最佳实践- **用 type 表角色,用 properties 表细节。** 让游戏 switch 的 `type` 值保持小而稳定,把易变的diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdxindex a5104eb9e..7bf6516e5 100644--- a/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx+++ b/docs/astro/src/content/docs/zh-cn/gameplay/physics.mdx@@ -234,6 +234,29 @@ const swept = physics.shapeCastCircle(/* … */); // sweep a shape| `normal` | `Vec2` | 命中点处的表面法线(单位向量)。 || `fraction` | number | 命中处占投射距离的比例,`0..1`——结果按它排序,最近优先。 |+## 在网格上放置++建造模式在手指拖着东西划过地面时要问三件事,`esengine/gameplay` 把它们做成了纯函数(没有组件,也没有系统):这个东西吸附到网格后落在哪里,它能不能站在那里。跟着手指走的幽灵精灵、怎么着色、确认放置之后做什么,都由你来定。++```typescript+import { snapFootprint, checkPlacement, type PlacementGrid } from 'esengine/gameplay';++const grid: PlacementGrid = { cellWidth: 32, cellHeight: 32 }; // 格子 (0, 0) 不在世界原点时再写 originX / originY+const spot = snapFootprint(grid, fingerX, fingerY, 3, 1); // 3×1 的墙,以中间那格为中心+ghost.position.x = spot.x; ghost.position.y = spot.y; // 幽灵落在整格上++const check = checkPlacement(grid, spot, {+ physics, // Physics2D 资源:占地范围内的任何碰撞体都算挡路+ mask: SOLID_LAYERS,+ solidAt: (x, y) => isTileSolid(layer, ...), // 脚下有实心瓦片就挡(见瓦片地图指南)+ blocked: (col, row) => buildings.has(col, row), // 你自己记录的"已被占用"+ ignore: new Set([ghostEntity]),+});+ghostSprite.color = check.clear ? GREEN : RED; // check.blockers 和 check.blockedCells 说明挡路的是什么+```++`snapToGrid` 把一个点吸附到格子中心或最近的格角;`gridCellAt` 和 `gridCellCentre` 在格子与世界坐标之间换算。奇数大小的占地以格子中心为中心,偶数大小的以格角为中心,横竖各自处理。每个探测都是可选的,不传的那个什么也不挡。`solidAt` 在每个格子上按网格采样(每隔 `solidStep`,默认四分之一格),比这更窄的实心瓦片可能从采样点之间漏过去;物理查询只问一次,占地范围缩小了一点点,所以只是边贴着墙不算挡路。+## 碰撞与传感事件`Physics2DEvents` 资源携带这一帧的接触。给碰撞体设 `isSensor: true` 即可得到 enter/exit 事件diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 82debbab7..0fcf69743 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 115,"beta": 171,- "experimental": 2715,+ "experimental": 2730,"deprecated": 3},- "total": 3001,+ "total": 3016,"subsystems": [{"id": "mobile-controls",diff --git a/sdk/etc/gameplay.api.md b/sdk/etc/gameplay.api.mdindex e026fd6be..42a1e0071 100644--- a/sdk/etc/gameplay.api.md+++ b/sdk/etc/gameplay.api.md@@ -1,7 +1,7 @@# API surface — esengine/gameplay<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 0 public · 0 beta · 50 experimental · 0 deprecated+Symbols: 0 public · 0 beta · 65 experimental · 0 deprecated## ATTACK_KEY — const @experimental```@@ -52,6 +52,12 @@ static new (): GameplayPluginstatic prototype: GameplayPlugin```+## GridCell — interface @experimental+```+col: number+row: number+```+## Health — const @experimental```ComponentDef<HealthData>@@ -131,6 +137,66 @@ forward: Vec3right: Vec3```+## NearEntity — interface @experimental+```+distance: number+entity: number+x: number+y: number+```++## NearestOptions — interface @experimental+```+filter: ((entity: Entity, data: D) => boolean) | undefined+limit: number | undefined+plane: "xz" | "xy" | undefined+radius: number | undefined+```++## PlacementCheck — interface @experimental+```+blockedCells: GridCell[]+blockers: number[]+clear: boolean+```++## PlacementGrid — interface @experimental+```+cellHeight: number+cellWidth: number+originX: number | undefined+originY: number | undefined+```++## PlacementProbes — interface @experimental+```+blocked: ((col: number, row: number) => boolean) | undefined+ignore: ReadonlySet<number> | undefined+mask: number | undefined+physics: { overlapAABB(min: { x: number; y: number; }, max: { x: number; y: number; }, maskBits?: number): Entity[]; } | undefined+solidAt: ((x: number, y: number) => boolean) | undefined+solidStep: number | undefined+```++## PlacementRect — interface @experimental+```+maxX: number+maxY: number+minX: number+minY: number+```++## SnappedFootprint — interface @experimental+```+col: number+cols: number+rect: PlacementRect+row: number+rows: number+x: number+y: number+```+## TPC_ATTACK — const @experimental```"attack"@@ -217,6 +283,11 @@ MoveBasis(yawDeg: number): { forward: Vec3; right: Vec3; }```+## checkPlacement — function @experimental+```+(grid: PlacementGrid, footprint: SnappedFootprint, probes?: PlacementProbes): PlacementCheck+```+## clampPitch — function @experimental```(pitch: number, min: number, max: number): number@@ -247,11 +318,31 @@ MoveBasisGameplayPlugin```+## gridCellAt — function @experimental+```+(grid: PlacementGrid, x: number, y: number): GridCell+```++## gridCellCentre — function @experimental+```+(grid: PlacementGrid, col: number, row: number): { x: number; y: number; }+```+## huntTargets — function @experimental```(world: World, animator: AnimatorControllerAPI | null, attackTrigger: string, dt: number): void```+## nearestEntities — function @experimental+```+<D>(world: World, component: ComponentDef<D>, from: { x: number; y: number; }, options?: NearestOptions<D>): NearEntity[]+```++## nearestMarkers — function @experimental+```+(world: World, from: { x: number; y: number; }, options?: Omit<NearestOptions<MarkerData>, "filter"> & { type?: string | readonly string[]; has?: Readonly<Record<string, string>>; }): NearEntity[]+```+## observeMotion — function @experimental```(world: World, animator: AnimatorControllerAPI | null, dt: number): void@@ -287,6 +378,16 @@ GameplayPlugin(from: number, to: number): number```+## snapFootprint — function @experimental+```+(grid: PlacementGrid, x: number, y: number, cols: number, rows: number): SnappedFootprint+```++## snapToGrid — function @experimental+```+(grid: PlacementGrid, x: number, y: number, mode?: "centre" | "corner"): { x: number; y: number; col: number; row: number; }+```+## turnToward — function @experimental```(from: number, to: number, degreesPerSecond: number, dt: number): numberdiff --git a/sdk/src/gameplay/index.ts b/sdk/src/gameplay/index.tsindex 653f0caec..f0ba39ff0 100644--- a/sdk/src/gameplay/index.ts+++ b/sdk/src/gameplay/index.ts@@ -73,3 +73,24 @@ export {import { registerGameplaySupport } from './gameplaySupport';registerGameplaySupport();++export {+ gridCellAt,+ gridCellCentre,+ snapToGrid,+ snapFootprint,+ checkPlacement,+ type PlacementGrid,+ type GridCell,+ type PlacementRect,+ type SnappedFootprint,+ type PlacementProbes,+ type PlacementCheck,+} from './placement';++export {+ nearestEntities,+ nearestMarkers,+ type NearEntity,+ type NearestOptions,+} from './nearest';diff --git a/sdk/src/gameplay/nearest.ts b/sdk/src/gameplay/nearest.tsnew file mode 100644index 000000000..473ba88f8--- /dev/null+++ b/sdk/src/gameplay/nearest.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file nearest.ts+ * @brief The entities of a kind that stand nearest a point: the one thing an "interact" button needs to know before it decides what it does.+ *+ * @details {@link nearestEntities} walks the entities that carry a component and a `Transform`, keeps the ones within a radius that pass the game's filter, and+ * returns them nearest first. {@link nearestMarkers} is the same over `Marker`, whose `type` is the game's own word for what an entity is (a door, a+ * tree, a bed). What the button DOES for each kind, and which kinds count, are the game's: the engine says what is near and how far, and the game+ * maps that to a verb.+ *+ * The distance is measured on the screen plane (x and y) by default, or on the ground (x and z) with `plane: 'xz'`, from each entity's world position.+ * An entity switched off with `Disabled` is not found. The cost is one pass over the entities that carry the component, which is what a button+ * press or a once-a-frame prompt can afford over the hundreds of things a village holds; a world of many thousands wants a spatial index of its own.+ */+import type { ComponentDef } from '../ecs/component';+import { Disabled, Marker, Transform, type MarkerData, type TransformData } from '../ecs/component';+import type { World } from '../ecs/world';+import type { Entity } from '../types';++/** One entity found, how far it is from the point, and where it stands. */+export interface NearEntity {+ entity: Entity;+ distance: number;+ x: number;+ y: number;+}++/** @experimental */+export interface NearestOptions<D> {+ /** The farthest an entity may be and still be found, in world units (default: any distance). */+ radius?: number;+ /** The most entities returned, nearest first (default: all of them). */+ limit?: number;+ /** Whether an entity counts: asked with its component's data, after the radius. */+ filter?(entity: Entity, data: D): boolean;+ /** Which two world axes the distance is measured on: the screen plane (default) or the ground. */+ plane?: 'xy' | 'xz';+}++/** The entities carrying `component`, within `options.radius` of `from` and passing `options.filter`, nearest first. */+export function nearestEntities<D>(+ world: World, component: ComponentDef<D>, from: { x: number; y: number }, options: NearestOptions<D> = {},+): NearEntity[] {+ world.ensureTransformsComposed();+ const radius = options.radius ?? Infinity;+ const ground = options.plane === 'xz';+ const found: NearEntity[] = [];+ for (const entity of world.getEntitiesWithComponents([component, Transform])) {+ if (world.has(entity, Disabled)) continue;+ const at = (world.get(entity, Transform) as TransformData).worldPosition;+ const y = ground ? at.z : at.y;+ const distance = Math.hypot(at.x - from.x, y - from.y);+ if (distance > radius) continue;+ if (options.filter && !options.filter(entity, world.get(entity, component) as D)) continue;+ found.push({ entity, distance, x: at.x, y });+ }+ found.sort((a, b) => a.distance - b.distance);+ return options.limit !== undefined ? found.slice(0, Math.max(options.limit, 0)) : found;+}++/**+ * The markers near a point, nearest first. `type` keeps only markers of that type (or any of several); `has` keeps only those whose `properties` carry every+ * given key and value.+ */+export function nearestMarkers(+ world: World, from: { x: number; y: number },+ options: Omit<NearestOptions<MarkerData>, 'filter'> & { type?: string | readonly string[]; has?: Readonly<Record<string, string>> } = {},+): NearEntity[] {+ const types = options.type === undefined ? null : typeof options.type === 'string' ? [options.type] : options.type;+ const { type: _type, has, ...rest } = options;+ return nearestEntities(world, Marker, from, {+ ...rest,+ filter: (_entity, marker) => (types === null || types.includes(marker.type))+ && (has === undefined || Object.entries(has).every(([key, value]) => marker.properties[key] === value)),+ });+}diff --git a/sdk/src/gameplay/placement.ts b/sdk/src/gameplay/placement.tsnew file mode 100644index 000000000..795ed0aa5--- /dev/null+++ b/sdk/src/gameplay/placement.ts@@ -0,0 +1,152 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file placement.ts+ * @brief The questions a build mode asks while a finger drags something over the ground: which cell is this, where does it sit snapped, and may it stand there.+ *+ * @details Three pure pieces and no system. {@link snapToGrid} and {@link snapFootprint} turn a free point into the place a thing of a given size sits on a grid+ * (a 3 by 1 wall centres on the middle of its middle cell, a 2 by 2 table on a corner). {@link checkPlacement} says whether that place is clear: no+ * collider of the physics world in it, no solid tile under it, nothing the game's own occupancy says is there, and it names what is in the way. What+ * follows the finger (a ghost sprite), what it is tinted, what may be placed on what, and what a confirmed placement does are the game's: the+ * engine answers the question each frame and the game draws the answer.+ *+ * The probes are handed in rather than looked up, so a game that has no physics, or no tilemap, or keeps its buildings in its own table, passes the+ * ones it has, and this module pulls in none of them.+ */+import type { Entity } from '../types';++/** A grid the world is built on: the size of one cell, and where the corner of cell (0, 0) lies. */+export interface PlacementGrid {+ cellWidth: number;+ cellHeight: number;+ originX?: number;+ originY?: number;+}++/** One cell of a grid, by column and row. */+export interface GridCell {+ col: number;+ row: number;+}++/** A rectangle in the world. */+export interface PlacementRect {+ minX: number;+ minY: number;+ maxX: number;+ maxY: number;+}++/** The cell a world point falls in. */+export function gridCellAt(grid: PlacementGrid, x: number, y: number): GridCell {+ return {+ col: Math.floor((x - (grid.originX ?? 0)) / grid.cellWidth),+ row: Math.floor((y - (grid.originY ?? 0)) / grid.cellHeight),+ };+}++/** The middle of a cell, in the world. */+export function gridCellCentre(grid: PlacementGrid, col: number, row: number): { x: number; y: number } {+ return {+ x: (grid.originX ?? 0) + (col + 0.5) * grid.cellWidth,+ y: (grid.originY ?? 0) + (row + 0.5) * grid.cellHeight,+ };+}++/** The point snapped to the middle of the cell it is in (`'centre'`, the default) or to the nearest cell corner (`'corner'`). */+export function snapToGrid(grid: PlacementGrid, x: number, y: number, mode: 'centre' | 'corner' = 'centre'): { x: number; y: number; col: number; row: number } {+ if (mode === 'corner') {+ const col = Math.round((x - (grid.originX ?? 0)) / grid.cellWidth);+ const row = Math.round((y - (grid.originY ?? 0)) / grid.cellHeight);+ return { x: (grid.originX ?? 0) + col * grid.cellWidth, y: (grid.originY ?? 0) + row * grid.cellHeight, col, row };+ }+ const cell = gridCellAt(grid, x, y);+ const centre = gridCellCentre(grid, cell.col, cell.row);+ return { x: centre.x, y: centre.y, ...cell };+}++/** Where a thing `cols` by `rows` cells big sits when its middle is dragged to a point: snapped so it covers whole cells. */+export interface SnappedFootprint {+ /** The middle of the footprint, in the world: where the ghost is drawn. */+ x: number;+ y: number;+ /** The lowest cell it covers, and how many it covers each way. */+ col: number;+ row: number;+ cols: number;+ rows: number;+ rect: PlacementRect;+}++/**+ * Snaps a footprint of `cols` by `rows` cells to the grid by its middle: an odd count centres on a cell, an even one on a cell corner, each way on its own, so+ * the footprint always covers whole cells and the finger stays in the middle of it.+ */+export function snapFootprint(grid: PlacementGrid, x: number, y: number, cols: number, rows: number): SnappedFootprint {+ const c = Math.max(Math.round(cols), 1), r = Math.max(Math.round(rows), 1);+ const gx = (x - (grid.originX ?? 0)) / grid.cellWidth, gy = (y - (grid.originY ?? 0)) / grid.cellHeight;+ // The footprint's lowest cell: its middle is half its size above it, and snapping the middle to whole or half cells is snapping this to whole cells.+ const col = Math.round(gx - c / 2), row = Math.round(gy - r / 2);+ const minX = (grid.originX ?? 0) + col * grid.cellWidth, minY = (grid.originY ?? 0) + row * grid.cellHeight;+ const maxX = minX + c * grid.cellWidth, maxY = minY + r * grid.cellHeight;+ return { x: (minX + maxX) / 2, y: (minY + maxY) / 2, col, row, cols: c, rows: r, rect: { minX, minY, maxX, maxY } };+}++/** What a placement is checked against. Each is optional; a probe not given blocks nothing. */+export interface PlacementProbes {+ /** The physics world: anything whose collider overlaps the footprint is in the way. */+ physics?: { overlapAABB(min: { x: number; y: number }, max: { x: number; y: number }, maskBits?: number): Entity[] };+ /** The collision layers the physics query asks about (all of them, by default). */+ mask?: number;+ /** Whether the ground at a world point is solid, as the game's tilemap says (`(x, y) => isTileSolid(...)`): a solid tile under any sampled point blocks. */+ solidAt?(x: number, y: number): boolean;+ /** The spacing of the points a cell is sampled at for `solidAt`, in world units (default a quarter of the smaller cell side): a solid tile narrower than this can slip between them. */+ solidStep?: number;+ /** Whether the game's own table says a cell is taken (a building already there, a zone it forbids). */+ blocked?(col: number, row: number): boolean;+ /** Entities that do not count as in the way: the thing being placed itself, and what it may stand among. */+ ignore?: ReadonlySet<Entity>;+}++/** What is in the way of a placement, or that nothing is. */+export interface PlacementCheck {+ clear: boolean;+ /** The colliders in the footprint, as the physics world lists them. */+ blockers: Entity[];+ /** The cells the tilemap or the game's table says are taken, by cell of the footprint. */+ blockedCells: GridCell[];+}++/**+ * Whether a snapped footprint may stand where it is. The physics probe is asked once, with the footprint's rectangle shrunk a hair so a wall that+ * only touches its edge is not in the way; the tilemap is sampled on a lattice over each cell it covers (every `solidStep`, a quarter of a cell by default);+ * the game's table is asked of every cell.+ */+export function checkPlacement(grid: PlacementGrid, footprint: SnappedFootprint, probes: PlacementProbes = {}): PlacementCheck {+ const blockedCells: GridCell[] = [];+ const inset = Math.min(grid.cellWidth, grid.cellHeight) * 0.02;+ const step = Math.max(probes.solidStep ?? Math.min(grid.cellWidth, grid.cellHeight) / 4, 1e-3);+ for (let r = 0; r < footprint.rows; r++) {+ for (let c = 0; c < footprint.cols; c++) {+ const col = footprint.col + c, row = footprint.row + r;+ let blocked = probes.blocked?.(col, row) === true;+ if (!blocked && probes.solidAt) {+ const x0 = (grid.originX ?? 0) + col * grid.cellWidth, y0 = (grid.originY ?? 0) + row * grid.cellHeight;+ const nx = Math.max(Math.ceil(grid.cellWidth / step), 1), ny = Math.max(Math.ceil(grid.cellHeight / step), 1);+ search: for (let j = 0; j < ny; j++) {+ for (let i = 0; i < nx; i++) {+ if (probes.solidAt((x0 + (i + 0.5) * grid.cellWidth / nx), (y0 + (j + 0.5) * grid.cellHeight / ny))) { blocked = true; break search; }+ }+ }+ }+ if (blocked) blockedCells.push({ col, row });+ }+ }+ let blockers: Entity[] = [];+ if (probes.physics) {+ const r = footprint.rect;+ const hit = probes.physics.overlapAABB({ x: r.minX + inset, y: r.minY + inset }, { x: r.maxX - inset, y: r.maxY - inset }, probes.mask);+ blockers = hit.filter((entity) => !probes.ignore?.has(entity));+ }+ return { clear: blockers.length === 0 && blockedCells.length === 0, blockers, blockedCells };+}diff --git a/sdk/tests/placement-queries.test.ts b/sdk/tests/placement-queries.test.tsnew file mode 100644index 000000000..5811a6a57--- /dev/null+++ b/sdk/tests/placement-queries.test.ts@@ -0,0 +1,140 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The two questions a build mode and an interact button ask: where does a footprint sit on the grid and may it stand there, and what is nearest.+ */+import { describe, expect, it } from 'vitest';+import {+ checkPlacement, gridCellAt, gridCellCentre, snapFootprint, snapToGrid, type PlacementGrid,+} from '../src/gameplay/placement';+import { nearestEntities, nearestMarkers } from '../src/gameplay/nearest';+import { Disabled, Marker, Transform } from '../src/ecs/component';+import type { World } from '../src/ecs/world';+import type { Entity } from '../src/types';++const grid: PlacementGrid = { cellWidth: 32, cellHeight: 32 };+const e = (n: number) => n as unknown as Entity;++describe('snapping to a grid', () => {+ it('finds the cell a point is in, and its middle, with an origin and with negatives', () => {+ expect(gridCellAt(grid, 40, 70)).toEqual({ col: 1, row: 2 });+ expect(gridCellAt(grid, -1, -33)).toEqual({ col: -1, row: -2 });+ expect(gridCellCentre(grid, 1, 2)).toEqual({ x: 48, y: 80 });+ const shifted: PlacementGrid = { cellWidth: 10, cellHeight: 10, originX: 5, originY: -5 };+ expect(gridCellAt(shifted, 5, -5)).toEqual({ col: 0, row: 0 });+ expect(gridCellCentre(shifted, 0, 0)).toEqual({ x: 10, y: 0 });+ });++ it('snaps a point to a cell middle or to the nearest corner', () => {+ expect(snapToGrid(grid, 40, 70)).toEqual({ x: 48, y: 80, col: 1, row: 2 });+ expect(snapToGrid(grid, 40, 70, 'corner')).toEqual({ x: 32, y: 64, col: 1, row: 2 });+ expect(snapToGrid(grid, 50, 81, 'corner')).toEqual({ x: 64, y: 96, col: 2, row: 3 });+ });++ it('snaps a footprint by its middle: odd counts on a cell, even on a corner, each way on its own', () => {+ const wall = snapFootprint(grid, 100, 40, 3, 1);+ expect(wall).toMatchObject({ col: 2, row: 1, cols: 3, rows: 1 });+ // 3 wide centres on the middle of the middle cell, 1 high on the middle of its cell.+ expect(wall.x).toBe(2 * 32 + 48);+ expect(wall.y).toBe(32 + 16);+ const table = snapFootprint(grid, 100, 100, 2, 2);+ expect(table.x % 32).toBe(0);+ expect(table.y % 32).toBe(0);+ expect(table.rect).toEqual({ minX: 64, minY: 64, maxX: 128, maxY: 128 });+ // Dragged a little the same cell, it stays; dragged past half a cell, it moves by one.+ expect(snapFootprint(grid, 102, 100, 2, 2).col).toBe(table.col);+ expect(snapFootprint(grid, 120, 100, 2, 2).col).toBe(table.col + 1);+ });+});++describe('whether a footprint may stand', () => {+ const one = snapFootprint(grid, 48, 48, 1, 1);+ const two = snapFootprint(grid, 64, 64, 2, 2);++ it('is clear with no probes at all', () => {+ expect(checkPlacement(grid, two)).toEqual({ clear: true, blockers: [], blockedCells: [] });+ });++ it('is blocked by what the physics world finds in it, less what is ignored, and asks once with the footprint shrunk a hair', () => {+ const asked: unknown[] = [];+ const physics = { overlapAABB: (min: { x: number; y: number }, max: { x: number; y: number }, mask?: number) => { asked.push([min, max, mask]); return [e(7), e(9)]; } };+ const result = checkPlacement(grid, two, { physics, mask: 0b10, ignore: new Set([e(9)]) });+ expect(result).toEqual({ clear: false, blockers: [e(7)], blockedCells: [] });+ expect(asked).toHaveLength(1);+ const [min, max, mask] = asked[0] as [{ x: number; y: number }, { x: number; y: number }, number];+ expect(min.x).toBeGreaterThan(two.rect.minX);+ expect(max.x).toBeLessThan(two.rect.maxX);+ expect(mask).toBe(0b10);+ expect(checkPlacement(grid, two, { physics, ignore: new Set([e(7), e(9)]) }).clear).toBe(true);+ });++ it('is blocked by a solid tile under any part of a cell it covers, and names the cell', () => {+ // A wall of tiles 8 wide along x = 70 to 78: the footprint (cells 1 and 2, x 32..96) is touched only in its second column.+ const result = checkPlacement(grid, snapFootprint(grid, 64, 64, 2, 2), { solidAt: (x) => x >= 70 && x <= 78 });+ expect(result.clear).toBe(false);+ expect(result.blockedCells.length).toBeGreaterThan(0);+ expect(result.blockedCells.every((c) => c.col === 2)).toBe(true);+ // A tile thinner than the sampling step can slip between the points, which is what the step is for.+ expect(checkPlacement(grid, snapFootprint(grid, 64, 64, 2, 2), { solidAt: (x) => x >= 70 && x <= 70.5, solidStep: 32 }).clear).toBe(true);+ expect(checkPlacement(grid, snapFootprint(grid, 64, 64, 2, 2), { solidAt: (x) => x >= 70 && x <= 70.5, solidStep: 0.25 }).clear).toBe(false);+ expect(checkPlacement(grid, one, { solidAt: () => false }).clear).toBe(true);+ });++ it('is blocked by a cell the game\'s own table says is taken', () => {+ const result = checkPlacement(grid, two, { blocked: (col, row) => col === 2 && row === 2 });+ expect(result).toEqual({ clear: false, blockers: [], blockedCells: [{ col: 2, row: 2 }] });+ });+});++/** A world that holds only what the query reads: which entities carry a component, where each stands, whether it is off. */+function fakeWorld(entities: { id: number; at: [number, number, number]; marker?: { type: string; properties?: Record<string, string> }; off?: boolean }[]): World {+ const byId = new Map(entities.map((x) => [x.id, x]));+ return {+ ensureTransformsComposed() {},+ getEntitiesWithComponents: (components: unknown[]) => entities.filter((x) => !components.includes(Marker) || x.marker).map((x) => e(x.id)),+ has: (entity: Entity, component: unknown) => component === Disabled && byId.get(entity as unknown as number)!.off === true,+ get: (entity: Entity, component: unknown) => {+ const x = byId.get(entity as unknown as number)!;+ if (component === Transform) return { worldPosition: { x: x.at[0], y: x.at[1], z: x.at[2] } };+ return { type: x.marker?.type ?? '', properties: x.marker?.properties ?? {} };+ },+ } as unknown as World;+}++describe('what is nearest', () => {+ const world = fakeWorld([+ { id: 1, at: [10, 0, 0], marker: { type: 'door' } },+ { id: 2, at: [3, 4, 0], marker: { type: 'tree', properties: { kind: 'oak' } } },+ { id: 3, at: [40, 0, 0], marker: { type: 'tree', properties: { kind: 'pine' } } },+ { id: 4, at: [1, 1, 0], marker: { type: 'tree' }, off: true },+ { id: 5, at: [0, 0, 8], marker: { type: 'bed' } },+ ]);++ it('lists what carries the component nearest first, within a radius, with how far', () => {+ const found = nearestEntities(world, Marker, { x: 0, y: 0 });+ expect(found.map((f) => f.entity)).toEqual([e(5), e(2), e(1), e(3)].filter((x) => found.some((f) => f.entity === x)));+ expect(found[0]).toMatchObject({ entity: e(5), distance: 0 });+ expect(found.find((f) => f.entity === e(2))!.distance).toBe(5);+ expect(nearestEntities(world, Marker, { x: 0, y: 0 }, { radius: 6 }).map((f) => f.entity)).toEqual([e(5), e(2)]);+ expect(nearestEntities(world, Marker, { x: 0, y: 0 }, { limit: 1 })).toHaveLength(1);+ });++ it('does not find what is switched off, and can measure on the ground instead', () => {+ expect(nearestEntities(world, Marker, { x: 0, y: 0 }).some((f) => f.entity === e(4))).toBe(false);+ const ground = nearestEntities(world, Marker, { x: 0, y: 0 }, { plane: 'xz', limit: 1 });+ // Seen from above, the bed at z 8 is far (8) and the oak at (3, z 0) is the nearest (3).+ expect(ground[0]).toMatchObject({ entity: e(2), distance: 3 });+ });++ it('takes a filter on the component\'s data', () => {+ const trees = nearestEntities(world, Marker, { x: 0, y: 0 }, { filter: (_e, marker) => marker.type === 'tree' });+ expect(trees.map((f) => f.entity)).toEqual([e(2), e(3)]);+ });++ it('finds markers by type, by several types, and by property', () => {+ expect(nearestMarkers(world, { x: 0, y: 0 }, { type: 'tree' }).map((f) => f.entity)).toEqual([e(2), e(3)]);+ expect(nearestMarkers(world, { x: 0, y: 0 }, { type: ['door', 'bed'] }).map((f) => f.entity)).toEqual([e(5), e(1)]);+ expect(nearestMarkers(world, { x: 0, y: 0 }, { type: 'tree', has: { kind: 'pine' } }).map((f) => f.entity)).toEqual([e(3)]);+ expect(nearestMarkers(world, { x: 0, y: 0 }, { radius: 1 })).toHaveLength(1);+ });+});