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(physics): the 3D world can be asked what is where
esengine30e067d8a0da
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bbd64dd2d..4a8e1b8e7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,16 @@ published separately; it ships inside the editor.### Added+- **Spatial queries with a shape, not just a line.** The `Physics3D` resource+ answers `sphereCast`, `overlapSphere` and `overlapBox` alongside `raycast`, all+ in world units and all narrowable by layer. A ray is infinitely thin and slips+ through the very gaps a moving body would not fit, so "can this thing get+ there" was a question the world could not be asked.++ A layer mask of 0 means EVERY layer rather than none: a caller that did not ask+ to filter is asking for everything, and the other reading would make the+ commonest call return silently empty.+- **3D collision layers.** Every body is in one of sixteen layers, and a projectsays which layers hear from which — bullets that pass through their own teamand stop on the world, which two layers could not express. Both sides mustdiff --git a/docs/astro/src/content/docs/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/gameplay/physics-3d.mdxindex c790be64b..049b5c52e 100644--- a/docs/astro/src/content/docs/gameplay/physics-3d.mdx+++ b/docs/astro/src/content/docs/gameplay/physics-3d.mdx@@ -95,6 +95,38 @@ if (input.justPressed('jump') && c.isOnFloor) c.velocity.y = 500;leaving every caller to rediscover it.</Aside>+## Asking the world what is where++The `Physics3D` resource answers spatial questions in world units.++```typescript+const q = app.getResource(Physics3D);++// Is anything on this line?+const hit = q.raycast(muzzle, { x: 0, y: 0, z: -2000 }, ENEMIES);++// Can this thing GET there? A ray is infinitely thin and slips through gaps a+// moving body would not fit — that is what a swept shape answers instead.+const blocked = q.sphereCast(from, 30, travel, WORLD);++// What is already here, before something is spawned into it?+const occupants = q.overlapSphere(spawnPoint, 50);+```++| Query | Answers |+|---|---|+| `raycast` | The nearest body on a line. |+| `sphereCast` | The first body a moving sphere would meet. |+| `overlapSphere` / `overlapBox` | Every body already inside a volume. |++<Aside>+ A layer mask of `0` means EVERY layer, not none: a caller that did not ask to+ filter is asking for everything, and the other reading would make the commonest+ call return silently empty. Hit normals come back unscaled — they are+ directions, and multiplying one by `pixelsPerUnit` leaves a unit vector 100+ units long.+</Aside>+## Collision layersEvery body is in one of sixteen layers, and a project says which layers hear fromdiff --git a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdxindex 44a913958..306b59741 100644--- a/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx+++ b/docs/astro/src/content/docs/zh-cn/gameplay/physics-3d.mdx@@ -87,6 +87,36 @@ if (input.justPressed('jump') && c.isOnFloor) c.velocity.y = 500;而不是让每个调用者各自重新发现这件事。</Aside>+## 问世界「那里有什么」++`Physics3D` 资源用世界单位回答空间问题。++```typescript+const q = app.getResource(Physics3D);++// 这条线上有东西吗?+const hit = q.raycast(muzzle, { x: 0, y: 0, z: -2000 }, ENEMIES);++// 这个东西「过得去」吗?射线是无限细的,会从一个运动刚体根本挤不过去的缝里穿过——+// 这正是扫掠形状回答的那个不同的问题。+const blocked = q.sphereCast(from, 30, travel, WORLD);++// 在往这里放东西之前,这里已经有什么了?+const occupants = q.overlapSphere(spawnPoint, 50);+```++| 查询 | 回答 |+|---|---|+| `raycast` | 一条线上最近的刚体。 |+| `sphereCast` | 一个运动的球最先撞上的刚体。 |+| `overlapSphere` / `overlapBox` | 已经在某个体积里的所有刚体。 |++<Aside>+ 层掩码为 `0` 表示**所有层**,不是「一个都不要」:没有要求过滤的调用者是在要全部,+ 而另一种读法会让最常见的调用悄悄返回空。命中法线**不做单位换算**——它是方向,+ 乘上 `pixelsPerUnit` 只会得到一个长度 100 的单位向量。+</Aside>+## 碰撞层每个刚体属于十六层中的一层,由项目声明哪些层之间能互相听见。**两边都得同意**——diff --git a/sdk/src/physics3d/Physics3DModule.ts b/sdk/src/physics3d/Physics3DModule.tsindex 9e7e30a25..816357dfe 100644--- a/sdk/src/physics3d/Physics3DModule.ts+++ b/sdk/src/physics3d/Physics3DModule.ts@@ -62,7 +62,13 @@ export interface Physics3DWasmModule {pz: number): void;_physics3d_raycast(ox: number, oy: number, oz: number,- dx: number, dy: number, dz: number): number;+ dx: number, dy: number, dz: number, layerMask: number): number;+ _physics3d_sphereCast(px: number, py: number, pz: number, radius: number,+ dx: number, dy: number, dz: number, layerMask: number): number;+ _physics3d_overlapSphere(px: number, py: number, pz: number, radius: number,+ layerMask: number): number;+ _physics3d_overlapBox(px: number, py: number, pz: number,+ hx: number, hy: number, hz: number, layerMask: number): number;_physics3d_contactEnters(): number;_physics3d_contactEntersBytes(): number;@@ -94,6 +100,7 @@ const REQUIRED_EXPORTS = ['_physics3d_removeBody', '_physics3d_setTransform', '_physics3d_raycast','_physics3d_transforms', '_physics3d_transformsBytes','_physics3d_addCharacter', '_physics3d_moveCharacter', '_physics3d_removeCharacter',+ '_physics3d_sphereCast', '_physics3d_overlapSphere', '_physics3d_overlapBox','_physics3d_contactEnters', '_physics3d_contactEntersBytes','_physics3d_sensorEnters', '_physics3d_sensorEntersBytes',] as const;diff --git a/sdk/src/physics3d/Physics3DPlugin.ts b/sdk/src/physics3d/Physics3DPlugin.tsindex 3537a0578..d5955a71e 100644--- a/sdk/src/physics3d/Physics3DPlugin.ts+++ b/sdk/src/physics3d/Physics3DPlugin.ts@@ -15,6 +15,10 @@ import {import {stepPhysics3D, DEFAULT_PHYSICS3D_CONFIG, type Physics3DConfig,} from './Physics3DSystem';+import { Physics3DQueries } from './Physics3DQueries';++/** Ask the 3D world what is where. Present once the module has loaded. */+export const Physics3D = defineResource<Physics3DQueries | null>(null, 'Physics3D');/** The live module and the promise that resolves it, for a caller that must wait. */export interface Physics3DRuntime {@@ -66,6 +70,8 @@ export class Physics3DPlugin implements Plugin {module._physics3d_setLayerMask(layer, mask);});runtime.module = module;+ app.insertResource(Physics3D, new Physics3DQueries(module,+ this.config_.pixelsPerUnit));app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([], () => {stepPhysics3D(app, module, runtime.bodies, this.config_,runtime.characters, events);diff --git a/sdk/src/physics3d/Physics3DQueries.ts b/sdk/src/physics3d/Physics3DQueries.tsnew file mode 100644index 000000000..739bbc2c2--- /dev/null+++ b/sdk/src/physics3d/Physics3DQueries.ts@@ -0,0 +1,122 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Physics3DQueries.ts+ * @brief Asking the 3D world what is where, in the units a scene is authored in.+ * @details Every distance crosses in metres and comes back in world units, the+ * same contract the step follows — a query answering in the solver's+ * units would be a second set of numbers for a caller to remember.+ */+import type { Entity } from '../types';+import type { Physics3DWasmModule } from './Physics3DModule';++/** Where a cast met something, in world units. */+export interface Cast3DHit {+ entity: Entity;+ /** How far along the cast, 0..1. */+ fraction: number;+ x: number;+ y: number;+ z: number;+ normalX: number;+ normalY: number;+ normalZ: number;+}++/** One body an overlap test found, and a point where it touches. */+export interface Overlap3DHit {+ entity: Entity;+ x: number;+ y: number;+ z: number;+}++/**+ * The 3D world's spatial queries.+ *+ * A layer mask of 0 means every layer: a caller that did not ask to filter is+ * asking for everything, and answering "nothing" there would be a silent empty+ * result for the commonest call.+ */+export class Physics3DQueries {+ constructor(private readonly module_: Physics3DWasmModule,+ private readonly ppu_: number) {}++ /** The nearest body along a ray, or null. `direction` carries its length. */+ raycast(origin: { x: number; y: number; z: number },+ direction: { x: number; y: number; z: number },+ layerMask = 0): Cast3DHit | null {+ const p = this.ppu_;+ const hit = this.module_._physics3d_raycast(+ origin.x / p, origin.y / p, origin.z / p,+ direction.x / p, direction.y / p, direction.z / p, layerMask);+ return hit ? this.readCast_() : null;+ }++ /**+ * Sweeps a sphere along `direction` and returns the first body it meets.+ *+ * What a ray cannot answer: a ray is infinitely thin, so it passes through+ * the very gaps a moving body would not fit — "can this thing get there" is+ * a different question from "is anything on this line".+ */+ sphereCast(origin: { x: number; y: number; z: number }, radius: number,+ direction: { x: number; y: number; z: number },+ layerMask = 0): Cast3DHit | null {+ const p = this.ppu_;+ const hit = this.module_._physics3d_sphereCast(+ origin.x / p, origin.y / p, origin.z / p, radius / p,+ direction.x / p, direction.y / p, direction.z / p, layerMask);+ return hit ? this.readCast_() : null;+ }++ /** Every body overlapping a sphere — what a spawn point asks before it spawns. */+ overlapSphere(centre: { x: number; y: number; z: number }, radius: number,+ layerMask = 0): Overlap3DHit[] {+ const p = this.ppu_;+ const count = this.module_._physics3d_overlapSphere(+ centre.x / p, centre.y / p, centre.z / p, radius / p, layerMask);+ return this.readOverlaps_(count);+ }++ /** The same for a box, given its half-extents. */+ overlapBox(centre: { x: number; y: number; z: number },+ halfExtents: { x: number; y: number; z: number },+ layerMask = 0): Overlap3DHit[] {+ const p = this.ppu_;+ const count = this.module_._physics3d_overlapBox(+ centre.x / p, centre.y / p, centre.z / p,+ halfExtents.x / p, halfExtents.y / p, halfExtents.z / p, layerMask);+ return this.readOverlaps_(count);+ }++ private readCast_(): Cast3DHit {+ const f32 = this.module_.HEAPF32;+ const o = this.module_._physics3d_queryResult() >> 2;+ const p = this.ppu_;+ return {+ entity: f32[o] as Entity,+ fraction: f32[o + 1]!,+ x: f32[o + 2]! * p, y: f32[o + 3]! * p, z: f32[o + 4]! * p,+ // A normal is a direction, so it is NOT scaled: multiplying it would+ // leave a unit vector 100 units long.+ normalX: f32[o + 5]!, normalY: f32[o + 6]!, normalZ: f32[o + 7]!,+ };+ }++ private readOverlaps_(count: number): Overlap3DHit[] {+ if (count <= 0) return [];+ const f32 = this.module_.HEAPF32;+ const base = this.module_._physics3d_queryResult() >> 2;+ const p = this.ppu_;+ const out: Overlap3DHit[] = [];+ for (let i = 0; i < count; i++) {+ const o = base + i * 4;+ out.push({+ entity: f32[o] as Entity,+ x: f32[o + 1]! * p, y: f32[o + 2]! * p, z: f32[o + 3]! * p,+ });+ }+ return out;+ }+}diff --git a/sdk/tests/physics3d-ecs.test.ts b/sdk/tests/physics3d-ecs.test.tsindex e6517f5d2..e1b6df471 100644--- a/sdk/tests/physics3d-ecs.test.ts+++ b/sdk/tests/physics3d-ecs.test.ts@@ -24,6 +24,7 @@ import type { Physics3DWasmModule } from '../src/physics3d/Physics3DModule';import type { App } from '../src/app/app';import type { Entity } from '../src/types';import { sceneUses3DPhysics, sceneUsesPhysics } from '../src/runtime/runtimeLoader';+import { Physics3DQueries } from '../src/physics3d/Physics3DQueries';/** A module that records what it was told, and can be made to answer a readback.* The two readbacks are separate buffers, as they are in the module: sharing one@@ -384,3 +385,60 @@ describe('mesh collision geometry', () => {])).toBeNull();});});++describe('3D spatial queries', () => {+ /** A module that answers one canned result, so the units can be checked. */+ function queryModule(result: number[], hits = 1) {+ const heap = new Float32Array(64);+ heap.set(result, 0);+ const calls: number[][] = [];+ return {+ calls,+ HEAPF32: heap,+ _physics3d_queryResult: () => 0,+ _physics3d_raycast: (...args: number[]) => { calls.push(args); return hits; },+ _physics3d_sphereCast: (...args: number[]) => { calls.push(args); return hits; },+ _physics3d_overlapSphere: (...args: number[]) => { calls.push(args); return hits; },+ _physics3d_overlapBox: (...args: number[]) => { calls.push(args); return hits; },+ } as unknown as Parameters<typeof Physics3DQueries.prototype.raycast> extends never+ ? never : ConstructorParameters<typeof Physics3DQueries>[0] & { calls: number[][] };+ }++ it('asks in metres and answers in world units', () => {+ // A hit 3m along, at 2m up, with an upward normal.+ const module = queryModule([9, 0.5, 0, 2, 0, 0, 1, 0]);+ const q = new Physics3DQueries(module, 100);+ const hit = q.raycast({ x: 0, y: 500, z: 0 }, { x: 0, y: -600, z: 0 });++ expect(module.calls[0]![1]).toBeCloseTo(5, 6); // 500 units = 5m+ expect(module.calls[0]![4]).toBeCloseTo(-6, 6);+ expect(hit!.y).toBeCloseTo(200, 4); // 2m = 200 units+ // A normal is a direction: scaling it would leave a unit vector 100 long.+ expect(hit!.normalY).toBeCloseTo(1, 6);+ expect(hit!.entity).toBe(9);+ });++ it('scales a swept sphere’s radius too', () => {+ const module = queryModule([1, 0.25, 0, 0, 0, 0, 1, 0]);+ const q = new Physics3DQueries(module, 100);+ q.sphereCast({ x: 0, y: 0, z: 0 }, 30, { x: 400, y: 0, z: 0 });+ expect(module.calls[0]![3]).toBeCloseTo(0.3, 6);+ expect(module.calls[0]![4]).toBeCloseTo(4, 6);+ });++ it('reads every overlap the world reported', () => {+ const module = queryModule([7, 1, 2, 3, 8, 4, 5, 6], 2);+ const q = new Physics3DQueries(module, 100);+ const hits = q.overlapSphere({ x: 0, y: 0, z: 0 }, 50);+ expect(hits).toHaveLength(2);+ expect(hits[0]!.entity).toBe(7);+ expect(hits[1]!.entity).toBe(8);+ expect(hits[1]!.x).toBeCloseTo(400, 4);+ });++ it('answers an empty list rather than a phantom hit', () => {+ const module = queryModule([7, 1, 2, 3], 0);+ const q = new Physics3DQueries(module, 100);+ expect(q.overlapBox({ x: 0, y: 0, z: 0 }, { x: 10, y: 10, z: 10 })).toEqual([]);+ });+});diff --git a/sdk/tests/physics3d-smoke.mjs b/sdk/tests/physics3d-smoke.mjsindex 61589391c..396bd9f4d 100644--- a/sdk/tests/physics3d-smoke.mjs+++ b/sdk/tests/physics3d-smoke.mjs@@ -45,8 +45,26 @@ function bodyState(id) {return { x: f(0), y: f(1), z: f(2), vx: f(7), vy: f(8), vz: f(9) };}+function sphereCast(px, py, pz, radius, dx, dy, dz, mask = 0) {+ if (!m._physics3d_sphereCast(px, py, pz, radius, dx, dy, dz, mask)) return null;+ const base = m._physics3d_queryResult() >> 2;+ const f = (i) => m.HEAPF32[base + i];+ return { entity: f(0), fraction: f(1), x: f(2), y: f(3), z: f(4),+ nx: f(5), ny: f(6), nz: f(7) };+}++const raycastMasked = (ox, oy, oz, dx, dy, dz, mask) =>+ (m._physics3d_raycast(ox, oy, oz, dx, dy, dz, mask) ? readRay() : null);++function readRay() {+ const base = m._physics3d_queryResult() >> 2;+ const f = (i) => m.HEAPF32[base + i];+ return { entity: f(0), fraction: f(1), x: f(2), y: f(3), z: f(4),+ nx: f(5), ny: f(6), nz: f(7) };+}+function raycast(ox, oy, oz, dx, dy, dz) {- if (!m._physics3d_raycast(ox, oy, oz, dx, dy, dz)) return null;+ if (!m._physics3d_raycast(ox, oy, oz, dx, dy, dz, 0)) return null;const base = m._physics3d_queryResult() >> 2;const f = (i) => m.HEAPF32[base + i];return { entity: f(0), fraction: f(1), x: f(2), y: f(3), z: f(4),@@ -360,7 +378,53 @@ step(240);check('one side refusing is enough', near(bodyState(secondId).y, 0.2, 0.1),`y=${bodyState(secondId)?.y?.toFixed(4)} want 0.2`);-// ── 10) A removed body is gone from both the sweep and the getter ───────────+// ── 10) Queries with a shape, not just a line ──────────────────────────────+// Two pillars 0.8 apart on their own layer, so nothing else in this world can+// answer for them.+const PILLAR_LAYER = 7, MASK = 1 << PILLAR_LAYER;+const LEFT = 50, RIGHT = 51;+m._physics3d_addBox(LEFT, 0.25, 1, 0.25, 80, 1, -0.65, ...IDENTITY,+ ...FREE(STATIC, PILLAR_LAYER), 0.5, 0, 0);+m._physics3d_addBox(RIGHT, 0.25, 1, 0.25, 80, 1, 0.65, ...IDENTITY,+ ...FREE(STATIC, PILLAR_LAYER), 0.5, 0, 0);+m._physics3d_optimize();++const overlaps = (count) => {+ const base = m._physics3d_queryResult() >> 2;+ return Array.from({ length: count }, (_, i) => ({+ entity: m.HEAPF32[base + i * 4], x: m.HEAPF32[base + i * 4 + 1],+ }));+};++// A sphere over the gap touches neither pillar; widened, it touches both.+check('a small overlap finds nothing between them',+ m._physics3d_overlapSphere(80, 1, 0, 0.3, MASK) === 0);+const found = m._physics3d_overlapSphere(80, 1, 0, 0.6, MASK);+check('a wider one finds both', found === 2, `found ${found}`);+const names = overlaps(found).map((h) => h.entity).sort();+check('and names them', names.length === 2 && names[0] === LEFT && names[1] === RIGHT,+ JSON.stringify(names));++// A box query answers the same question in the shape a room is.+check('a box overlap finds them too',+ m._physics3d_overlapBox(80, 1, 0, 0.4, 0.5, 1, MASK) === 2);++// Layers narrow a query: nothing else lives on layer 6.+check('a query only sees the layers it asked for',+ m._physics3d_overlapSphere(80, 1, 0, 0.6, 1 << 6) === 0);++// ★ What a ray cannot answer. The gap is 0.8 wide, so an infinitely thin ray+// passes between the pillars while a 0.5-radius sphere — one metre across —+// cannot. This is the whole reason a shape cast exists.+check('a ray slips through the gap',+ raycastMasked(78, 1, 0, 6, 0, 0, MASK) === null);+const swept = sphereCast(78, 1, 0, 0.5, 6, 0, 0, MASK);+check('a swept sphere does not', swept != null, JSON.stringify(swept));+check('and stops at the pillars', swept != null && swept.fraction < 0.5+ && (swept.entity === LEFT || swept.entity === RIGHT),+ `entity=${swept?.entity} fraction=${swept?.fraction?.toFixed(4)}`);++// ── 11) A removed body is gone from both the sweep and the getter ───────────m._physics3d_removeBody(capId);step(1);check('a removed body leaves the readback', bodyPos(CAP) === null);diff --git a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cppindex 7eabac9e3..64348abbb 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp@@ -24,7 +24,10 @@#include <Jolt/Physics/Collision/Shape/MeshShape.h>#include <Jolt/Physics/Collision/Shape/SphereShape.h>#include <Jolt/Physics/Character/CharacterVirtual.h>+#include <Jolt/Physics/Collision/CollideShape.h>+#include <Jolt/Physics/Collision/CollisionCollectorImpl.h>#include <Jolt/Physics/Collision/ContactListener.h>+#include <Jolt/Physics/Collision/ShapeCast.h>#include <Jolt/RegisterTypes.h>#include <cstddef>@@ -503,15 +506,117 @@ void physics3d_setCharacterPosition(uint32_t characterId, float px, float py, fl// Queries+namespace {++/// Restricts a query to the layers a caller named. A zero mask means EVERY layer+/// rather than none: a caller that did not ask to filter is asking for+/// everything, and the other reading would silently return nothing.+class MaskLayerFilter final : public ObjectLayerFilter {+public:+ explicit MaskLayerFilter(uint32_t mask) : mask_(mask == 0 ? 0xFFFFFFFFu : mask) {}+ bool ShouldCollide(ObjectLayer layer) const override {+ return (mask_ & (1u << esengine::physics3d::Layers::indexOf(layer))) != 0;+ }+private:+ uint32_t mask_;+};++/// Appends one hit's (entity, px,py,pz) to the query buffer.+void pushHit(const BodyID& id, RVec3Arg point) {+ auto owner = g().entityOf.find(id.GetIndexAndSequenceNumber());+ g().queryBuffer.push_back(owner == g().entityOf.end() ? 0.0f+ : static_cast<float>(owner->second));+ g().queryBuffer.push_back(static_cast<float>(point.GetX()));+ g().queryBuffer.push_back(static_cast<float>(point.GetY()));+ g().queryBuffer.push_back(static_cast<float>(point.GetZ()));+}++/// Everything overlapping `shape` at `position`, into the query buffer.+int collideShape(const Shape* shape, float px, float py, float pz, uint32_t layerMask) {+ g().queryBuffer.clear();+ if (!g().isValid() || shape == nullptr) return 0;+ AllHitCollisionCollector<CollideShapeCollector> collector;+ const CollideShapeSettings settings;+ const RMat44 transform = RMat44::sTranslation(RVec3(px, py, pz));+ const MaskLayerFilter filter(layerMask);+ g().system->GetNarrowPhaseQuery().CollideShape(+ shape, Vec3::sReplicate(1.0f), transform, settings, RVec3::sZero(), collector,+ {}, filter);+ for (const CollideShapeResult& hit : collector.mHits) {+ pushHit(hit.mBodyID2, hit.mContactPointOn2);+ }+ return static_cast<int>(collector.mHits.size());+}++} // namespace++/**+ * @brief Everything a sphere at this position overlaps.+ * @details Writes (entity, px,py,pz) per hit into the query buffer and returns+ * how many — the question a spawn point asks before it spawns.+ */+EMSCRIPTEN_KEEPALIVE+int physics3d_overlapSphere(float px, float py, float pz, float radius, uint32_t layerMask) {+ if (radius <= 0.0f) { g().queryBuffer.clear(); return 0; }+ const SphereShape shape(radius);+ return collideShape(&shape, px, py, pz, layerMask);+}++/** @brief The same for a box, given its half-extents. */+EMSCRIPTEN_KEEPALIVE+int physics3d_overlapBox(float px, float py, float pz, float hx, float hy, float hz,+ uint32_t layerMask) {+ if (hx <= 0.0f || hy <= 0.0f || hz <= 0.0f) { g().queryBuffer.clear(); return 0; }+ const BoxShape shape(Vec3(hx, hy, hz));+ return collideShape(&shape, px, py, pz, layerMask);+}++/**+ * @brief Sweeps a sphere along a path and reports the first thing it meets.+ * @details What a ray cannot answer: a ray is infinitely thin, so it slips through+ * the very gaps a moving body would not fit. Writes+ * (entity, fraction, px,py,pz, nx,ny,nz); returns 0 for a clear path.+ */+EMSCRIPTEN_KEEPALIVE+int physics3d_sphereCast(float px, float py, float pz, float radius,+ float dx, float dy, float dz, uint32_t layerMask) {+ g().queryBuffer.clear();+ if (!g().isValid() || radius <= 0.0f) return 0;+ const SphereShape shape(radius);+ const RShapeCast cast(&shape, Vec3::sReplicate(1.0f),+ RMat44::sTranslation(RVec3(px, py, pz)), Vec3(dx, dy, dz));+ ClosestHitCollisionCollector<CastShapeCollector> collector;+ const ShapeCastSettings settings;+ const MaskLayerFilter filter(layerMask);+ g().system->GetNarrowPhaseQuery().CastShape(cast, settings, RVec3::sZero(), collector,+ {}, filter);+ if (!collector.HadHit()) return 0;++ const ShapeCastResult& hit = collector.mHit;+ auto owner = g().entityOf.find(hit.mBodyID2.GetIndexAndSequenceNumber());+ const RVec3 point = hit.mContactPointOn2;+ const Vec3 normal = -hit.mPenetrationAxis.Normalized();+ g().queryBuffer = {+ owner == g().entityOf.end() ? 0.0f : static_cast<float>(owner->second),+ hit.mFraction,+ static_cast<float>(point.GetX()), static_cast<float>(point.GetY()),+ static_cast<float>(point.GetZ()),+ normal.GetX(), normal.GetY(), normal.GetZ(),+ };+ return 1;+}+/// Nearest hit along the ray. Writes (entity, fraction, px,py,pz, nx,ny,nz) into the/// query buffer and returns 1; returns 0 and leaves it empty when nothing is hit.EMSCRIPTEN_KEEPALIVE-int physics3d_raycast(float ox, float oy, float oz, float dx, float dy, float dz) {+int physics3d_raycast(float ox, float oy, float oz, float dx, float dy, float dz,+ uint32_t layerMask) {g().queryBuffer.clear();if (!g().isValid()) return 0;const RRayCast ray{RVec3(ox, oy, oz), Vec3(dx, dy, dz)};RayCastResult hit;- if (!g().system->GetNarrowPhaseQuery().CastRay(ray, hit)) return 0;+ const MaskLayerFilter filter(layerMask);+ if (!g().system->GetNarrowPhaseQuery().CastRay(ray, hit, {}, filter)) return 0;const RVec3 point = ray.GetPointOnRay(hit.mFraction);const BodyLockRead lock(g().system->GetBodyLockInterface(), hit.mBodyID);