lecodes-cli 0.18.2 → 0.19.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/dist/index.js +1240 -170
- package/package.json +3 -2
- package/runtime/scene-harness.json +1 -1
- package/runtime/sdk/compile/aspectMacro.ts +86 -0
- package/runtime/sdk/compile/assetIconMacro.ts +384 -0
- package/runtime/sdk/compile/assetMacro.ts +146 -0
- package/runtime/sdk/compile/assetName.ts +50 -0
- package/runtime/sdk/compile/bundler.ts +287 -0
- package/runtime/sdk/compile/compileProject.ts +129 -0
- package/runtime/sdk/compile/detectEntry.ts +128 -0
- package/runtime/sdk/compile/fontMacro.ts +459 -0
- package/runtime/sdk/compile/fontRegistry.ts +78 -0
- package/runtime/sdk/compile/header.ts +67 -0
- package/runtime/sdk/compile/index.ts +100 -0
- package/runtime/sdk/compile/libraryImports.ts +52 -0
- package/runtime/sdk/compile/liteMaterial.ts +247 -0
- package/runtime/sdk/compile/sceneEditor.ts +88 -0
- package/runtime/sdk/compile/serverSplit.ts +233 -0
- package/runtime/sdk/compile/serverTypes.ts +227 -0
- package/runtime/sdk/compile/sfnt.ts +98 -0
- package/runtime/sdk/compile/shaderSchema.ts +202 -0
- package/runtime/sdk/compile/shaderTargets.ts +81 -0
- package/runtime/sdk/compile/sourcemap.ts +25 -0
- package/runtime/sdk/core/Aspect.ts +65 -9
- package/runtime/sdk/core/StateMachine.ts +308 -0
- package/runtime/sdk/core/time.ts +3 -0
- package/runtime/sdk/gl/CameraPlace.ts +52 -52
- package/runtime/sdk/gl/Light.ts +12 -4
- package/runtime/sdk/gl/Lightmap.ts +87 -10
- package/runtime/sdk/gl/Material.ts +15 -0
- package/runtime/sdk/gl/Model.ts +68 -8
- package/runtime/sdk/gl/NavAgent.ts +337 -0
- package/runtime/sdk/gl/NavMesh.ts +397 -0
- package/runtime/sdk/gl/Ragdoll.ts +270 -0
- package/runtime/sdk/gl/Scene.ts +7 -0
- package/runtime/sdk/gl/Shape.ts +37 -5
- package/runtime/sdk/gl/Terrain.ts +1092 -0
- package/runtime/sdk/gl/Texture.ts +17 -0
- package/runtime/sdk/gl/Trigger.ts +45 -45
- package/runtime/sdk/gl/animation/Animator.ts +35 -2
- package/runtime/sdk/gl/animation/Layer.ts +3 -1
- package/runtime/sdk/gl/animation/Loop.ts +5 -0
- package/runtime/sdk/gl/animation/Playback.ts +4 -3
- package/runtime/sdk/gl/animation/core.ts +52 -10
- package/runtime/sdk/gl/scenarios.ts +291 -291
- package/runtime/sdk/gl/state.ts +6 -6
- package/runtime/sdk/gl/terrainMesh.ts +219 -0
- package/runtime/sdk/inject.ts +12 -1
- package/runtime/sdk/net/codec.ts +119 -0
- package/runtime/sdk/net/core.ts +384 -0
- package/runtime/sdk/net/index.ts +181 -0
- package/runtime/sdk/net/replication.ts +622 -0
- package/runtime/sdk/scene/defineScene.ts +140 -14
- package/runtime/sdk/scene/editorPlugins.ts +18 -0
- package/runtime/sdk/scene/gizmos.ts +148 -148
- package/runtime/sdk/ui/UINode.ts +4 -0
- package/runtime/sdk-types.json +1 -1
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
// Navigation meshes (docs/navmesh-plan.md). A level bakes ONE navmesh at dev time from its static
|
|
2
|
+
// collision geometry (`lecodes navmesh bake` — the desktop host dumps every static Jolt body's
|
|
3
|
+
// triangles, Recast builds the mesh in the CLI) and loads it at runtime; agents (`NavAgent`) walk
|
|
4
|
+
// it through DetourCrowd, and the game asks it for paths, nearest points, walkability rays and
|
|
5
|
+
// random spots. A scene FILE does the loading by itself:
|
|
6
|
+
//
|
|
7
|
+
// env: { navmesh: { data: asset('./assets/nav/yard.navmesh'), agent: { radius: 0.4, height: 1.8 } } }
|
|
8
|
+
//
|
|
9
|
+
// Hand-built scenes call it once the level is complete:
|
|
10
|
+
//
|
|
11
|
+
// const nav = await NavMesh.load(scene, { data: asset('./assets/nav/yard.navmesh') })
|
|
12
|
+
// nav?.findPath(a, b) // Vec3[] corners (+ .partial)
|
|
13
|
+
// enemy.aspect(NavAgent, { speed: 3 }).agent.goTo(player.position)
|
|
14
|
+
//
|
|
15
|
+
// Under `lecodes navmesh bake` the same call is where the geometry dump fires ("the scene is
|
|
16
|
+
// complete"); on a host without navigation, or with a placeholder file, `load` resolves null and
|
|
17
|
+
// agents stay inert — the project runs everywhere. All logic lives here in JS; the native side
|
|
18
|
+
// (creator-nav) is the algorithms and the per-step hot path: ONE crowd update + ONE flat read per
|
|
19
|
+
// fixed step for every agent in the scene (`NavCrowd`, a system the mesh attaches to its scene).
|
|
20
|
+
|
|
21
|
+
import { fetch } from "../runtime/fetch"
|
|
22
|
+
import { System } from "../core/Aspect"
|
|
23
|
+
import { Vec3, cx, cy, cz, type Vec3Like } from "../math/vec"
|
|
24
|
+
import { Geometry } from "./Geometry"
|
|
25
|
+
import { Material } from "./Material"
|
|
26
|
+
import { Mesh } from "./Mesh"
|
|
27
|
+
import type { Node } from "./Node"
|
|
28
|
+
import type { Scene } from "./Scene"
|
|
29
|
+
import type { NavAgent } from "./NavAgent"
|
|
30
|
+
|
|
31
|
+
// Fixed-order layouts — keep in step with creator-nav/creator-nav.h (CNAV_AGENT_* / CNAV_READ_*).
|
|
32
|
+
export const NAV_AGENT = {
|
|
33
|
+
RADIUS: 0, HEIGHT: 1, MAX_SPEED: 2, MAX_ACCELERATION: 3, COLLISION_QUERY_RANGE: 4, PATH_OPTIMIZATION_RANGE: 5,
|
|
34
|
+
SEPARATION_WEIGHT: 6, AVOIDANCE: 7, INCLUDE_FLAGS: 8, EXCLUDE_FLAGS: 9, ANTICIPATE_TURNS: 10,
|
|
35
|
+
OPTIMIZE_VIS: 11, OPTIMIZE_TOPO: 12, COUNT: 13,
|
|
36
|
+
} as const
|
|
37
|
+
export const NAV_READ = {
|
|
38
|
+
POS_X: 0, POS_Y: 1, POS_Z: 2, VEL_X: 3, VEL_Y: 4, VEL_Z: 5, DVEL_X: 6, DVEL_Y: 7, DVEL_Z: 8,
|
|
39
|
+
STATE: 9, TARGET_STATE: 10, REMAINING: 11, PARTIAL: 12, STRIDE: 13,
|
|
40
|
+
} as const
|
|
41
|
+
const FLAGS_ALL = 0xffff
|
|
42
|
+
const AREA_UNWALKABLE = 255
|
|
43
|
+
const AREA_SKIP = 254
|
|
44
|
+
|
|
45
|
+
/** The agent size a navmesh is built for (and the crowd's defaults). */
|
|
46
|
+
export type NavAgentSize = {
|
|
47
|
+
/** metres — polygons are eroded by it. Default 0.4 */
|
|
48
|
+
radius?: number
|
|
49
|
+
/** metres. Default 1.8 */
|
|
50
|
+
height?: number
|
|
51
|
+
/** the highest step walked over, metres. Default 0.4 */
|
|
52
|
+
climb?: number
|
|
53
|
+
/** the steepest walkable slope, degrees. Default 50 */
|
|
54
|
+
slope?: number
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type NavMeshLoadOptions = {
|
|
58
|
+
/** `asset('./assets/nav/<scene>.navmesh')` — what `lecodes navmesh bake` writes. */
|
|
59
|
+
data: string
|
|
60
|
+
/** The agent size the bake uses (the file records it; the crowd reads it back). */
|
|
61
|
+
agent?: NavAgentSize
|
|
62
|
+
/** Named areas → traversal cost (1 = plain ground). Ids are assigned in this order (1..15); the
|
|
63
|
+
* bake stores the names, queries and agents refer to them (`include` / `exclude`, `cost`). */
|
|
64
|
+
areas?: Record<string, number>
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The file header `lecodes navmesh bake` wrote. */
|
|
68
|
+
export type NavMeshInfo = {
|
|
69
|
+
version: number
|
|
70
|
+
agent: { radius: number, height: number, climb: number, slope: number }
|
|
71
|
+
cell: number
|
|
72
|
+
cellHeight: number
|
|
73
|
+
tileSize: number
|
|
74
|
+
bounds: [[number, number, number], [number, number, number]]
|
|
75
|
+
stats: { tiles: number, polys: number, verts: number, triangles: number, volumes: number, links: number }
|
|
76
|
+
meta: { scene?: string, areas?: Record<string, number>, costs?: Record<string, number>, [k: string]: unknown } | null
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A straight path: the corners to walk, plus whether it stops short of the target. */
|
|
80
|
+
export type NavPath = Vec3[] & { partial: boolean }
|
|
81
|
+
|
|
82
|
+
export type NavQueryOptions = {
|
|
83
|
+
/** Only these areas (names). Default: every area. */
|
|
84
|
+
include?: string[]
|
|
85
|
+
/** Never these areas (names). */
|
|
86
|
+
exclude?: string[]
|
|
87
|
+
/** Search half-extents around each endpoint (how far off the mesh a point may be). Default [2, 4, 2]. */
|
|
88
|
+
extents?: Vec3Like
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export type NavRaycastHit = { hit: boolean, point: Vec3, normal: Vec3 }
|
|
92
|
+
|
|
93
|
+
type BakeConfig = { outDir: string, name?: string }
|
|
94
|
+
|
|
95
|
+
const bakeConfig = (): BakeConfig | null => {
|
|
96
|
+
const g = (globalThis as unknown as { __lecodesNavmesh?: BakeConfig }).__lecodesNavmesh
|
|
97
|
+
return g && typeof g.outDir === "string" ? g : null
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const hasNav = (): boolean => typeof _creatorNav !== "undefined" && _creatorNav !== null
|
|
101
|
+
|
|
102
|
+
const scratch = new Float32Array(6)
|
|
103
|
+
const pathScratch = new Float32Array(256 * 3)
|
|
104
|
+
|
|
105
|
+
/** The crowd behind a scene's agents — a system `NavMesh.load` attaches to the scene so the whole
|
|
106
|
+
* crowd advances once per fixed step, BEFORE every `NavAgent` applies its slot (`static after`). */
|
|
107
|
+
export class NavCrowd extends System<"navCrowd"> {
|
|
108
|
+
static readonly aspect = "navCrowd"
|
|
109
|
+
|
|
110
|
+
/** @internal */ _mesh: NavMesh | null = null
|
|
111
|
+
/** @internal */ _id = 0
|
|
112
|
+
/** @internal */ _max = 0
|
|
113
|
+
/** @internal */ _buf = new Float32Array(0)
|
|
114
|
+
/** @internal */ _agents = new Set<NavAgent>()
|
|
115
|
+
/** @internal */ _step = 0
|
|
116
|
+
|
|
117
|
+
/** @internal Make room for one more agent (the crowd is re-created with double the slots; every
|
|
118
|
+
* agent re-joins — slots change, targets are re-requested). */
|
|
119
|
+
_ensureCapacity(): boolean {
|
|
120
|
+
if (!this._mesh || !hasNav()) return false
|
|
121
|
+
if (this._id && this._agents.size < this._max) return true
|
|
122
|
+
const max = Math.max(16, this._max * 2)
|
|
123
|
+
const id = _creatorNav.crowdCreate(this._mesh.id, max, Math.max(0.6, this._mesh._maxRadius))
|
|
124
|
+
if (!id) { console.warn(`NavCrowd: ${_creatorNav.lastError()}`); return false }
|
|
125
|
+
const old = this._id
|
|
126
|
+
this._id = id
|
|
127
|
+
this._max = max
|
|
128
|
+
this._buf = new Float32Array(max * NAV_READ.STRIDE)
|
|
129
|
+
if (old) {
|
|
130
|
+
for (const a of this._agents) a._rejoin()
|
|
131
|
+
_creatorNav.crowdDestroy(old)
|
|
132
|
+
}
|
|
133
|
+
return true
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
updateFixed(dt: number): void {
|
|
137
|
+
if (!this._id) return
|
|
138
|
+
_creatorNav.crowdUpdate(this._id, dt)
|
|
139
|
+
_creatorNav.crowdRead(this._id, this._buf)
|
|
140
|
+
this._step++
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
onDetach(): void {
|
|
144
|
+
if (this._id && hasNav()) _creatorNav.crowdDestroy(this._id)
|
|
145
|
+
this._id = 0
|
|
146
|
+
this._max = 0
|
|
147
|
+
this._agents.clear()
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export class NavMesh {
|
|
152
|
+
/** True while `lecodes navmesh bake` runs the app — skip menus and build the level straight away. */
|
|
153
|
+
static get baking(): boolean { return bakeConfig() !== null }
|
|
154
|
+
|
|
155
|
+
/** The navmesh agents bind to (the last one loaded; one per world at a time). */
|
|
156
|
+
static active: NavMesh | null = null
|
|
157
|
+
|
|
158
|
+
private static byScene = new WeakMap<Scene, NavMesh>()
|
|
159
|
+
private static overrides = new Map<number, number | string>() // entity → area id / name / skip
|
|
160
|
+
private static warned = false
|
|
161
|
+
private static baked = false
|
|
162
|
+
|
|
163
|
+
/** Leave a static body out of the bake (`nav: false` in a scene file). */
|
|
164
|
+
static exclude(node: Node): void { NavMesh.overrides.set(node.id, AREA_SKIP) }
|
|
165
|
+
/** A static body nobody may walk on (`nav: 'unwalkable'`): its footprint is cut out. */
|
|
166
|
+
static unwalkable(node: Node): void { NavMesh.overrides.set(node.id, AREA_UNWALKABLE) }
|
|
167
|
+
/** A static body's surface belongs to a named area (`navArea: 'road'`; names from `load`'s `areas`). */
|
|
168
|
+
static area(node: Node, name: string): void { NavMesh.overrides.set(node.id, name) }
|
|
169
|
+
/** Forget every override (a scene rebuild). */
|
|
170
|
+
static clear(): void { NavMesh.overrides.clear() }
|
|
171
|
+
|
|
172
|
+
static of(scene: Scene): NavMesh | null { return NavMesh.byScene.get(scene) ?? null }
|
|
173
|
+
|
|
174
|
+
/** Load the level's navmesh — or, under `lecodes navmesh bake`, dump the collision geometry for
|
|
175
|
+
* it. Resolves null when nothing was loaded (no bake yet, a host without navigation, bake mode). */
|
|
176
|
+
static async load(scene: Scene, opts: NavMeshLoadOptions): Promise<NavMesh | null> {
|
|
177
|
+
const bake = bakeConfig()
|
|
178
|
+
if (bake) { NavMesh.bake(bake, opts); return null }
|
|
179
|
+
if (!hasNav()) {
|
|
180
|
+
if (!NavMesh.warned) { NavMesh.warned = true; console.warn("NavMesh: this host has no navigation support — agents stay still") }
|
|
181
|
+
return null
|
|
182
|
+
}
|
|
183
|
+
if (_creatorNav.ready) await _creatorNav.ready()
|
|
184
|
+
let id = 0
|
|
185
|
+
try {
|
|
186
|
+
const resp = await fetch(opts.data, { useOnce: true })
|
|
187
|
+
if (resp.status >= 400) { console.warn(`NavMesh: no navmesh at ${opts.data} (HTTP ${resp.status}) — run \`lecodes navmesh bake\``); return null }
|
|
188
|
+
id = _creatorNav.load((resp as unknown as { _id: number })._id)
|
|
189
|
+
resp.dispose()
|
|
190
|
+
} catch (e) {
|
|
191
|
+
console.warn(`NavMesh: could not read ${opts.data}: ${String(e)}`)
|
|
192
|
+
return null
|
|
193
|
+
}
|
|
194
|
+
if (!id) { console.warn(`NavMesh: ${opts.data}: ${_creatorNav.lastError()}`); return null }
|
|
195
|
+
let info: NavMeshInfo
|
|
196
|
+
try { info = JSON.parse(_creatorNav.header(id)) as NavMeshInfo } catch { info = { version: 0 } as NavMeshInfo }
|
|
197
|
+
if (!info.stats || info.stats.polys === 0) {
|
|
198
|
+
console.warn(`NavMesh: ${opts.data} is a placeholder — run \`lecodes navmesh bake\``)
|
|
199
|
+
_creatorNav.unload(id)
|
|
200
|
+
return null
|
|
201
|
+
}
|
|
202
|
+
const previous = NavMesh.byScene.get(scene)
|
|
203
|
+
if (previous) previous.dispose()
|
|
204
|
+
const nav = new NavMesh(scene, id, info, opts)
|
|
205
|
+
NavMesh.byScene.set(scene, nav)
|
|
206
|
+
NavMesh.active = nav
|
|
207
|
+
return nav
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
readonly scene: Scene
|
|
211
|
+
/** @internal the host handle */
|
|
212
|
+
readonly id: number
|
|
213
|
+
readonly info: NavMeshInfo
|
|
214
|
+
/** The agent size the mesh was built for. */
|
|
215
|
+
readonly agent: { radius: number, height: number, climb: number, slope: number }
|
|
216
|
+
/** Named areas → ids (from the bake; `load`'s `areas` when the file has none). */
|
|
217
|
+
readonly areas: Record<string, number>
|
|
218
|
+
/** @internal the largest agent radius seen (sizes the crowd's grid) */
|
|
219
|
+
_maxRadius = 0
|
|
220
|
+
private _debug: Mesh[] = []
|
|
221
|
+
private _seed = 0x9e3779b9
|
|
222
|
+
private _disposed = false
|
|
223
|
+
|
|
224
|
+
private constructor(scene: Scene, id: number, info: NavMeshInfo, opts: NavMeshLoadOptions) {
|
|
225
|
+
this.scene = scene
|
|
226
|
+
this.id = id
|
|
227
|
+
this.info = info
|
|
228
|
+
this.agent = info.agent ?? { radius: opts.agent?.radius ?? 0.4, height: opts.agent?.height ?? 1.8, climb: opts.agent?.climb ?? 0.4, slope: opts.agent?.slope ?? 50 }
|
|
229
|
+
this._maxRadius = this.agent.radius
|
|
230
|
+
this.areas = info.meta?.areas ?? NavMesh.areaIds(opts.areas)
|
|
231
|
+
const costs = { ...(info.meta?.costs ?? {}), ...(opts.areas ?? {}) }
|
|
232
|
+
for (const [ name, cost ] of Object.entries(costs)) this.cost(name, cost)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private static areaIds(areas: Record<string, number> | undefined): Record<string, number> {
|
|
236
|
+
const out: Record<string, number> = {}
|
|
237
|
+
let next = 1
|
|
238
|
+
for (const name of Object.keys(areas ?? {})) {
|
|
239
|
+
if (next > 15) { console.warn(`NavMesh: more than 15 areas — "${name}" ignored`); break }
|
|
240
|
+
out[name] = next++
|
|
241
|
+
}
|
|
242
|
+
return out
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** The include/exclude flag mask for a list of area names (undefined = every area). */
|
|
246
|
+
flags(names?: string[]): number {
|
|
247
|
+
if (!names) return FLAGS_ALL
|
|
248
|
+
let mask = 0
|
|
249
|
+
for (const n of names) {
|
|
250
|
+
const id = this.areas[n]
|
|
251
|
+
if (id === undefined) { console.warn(`NavMesh: unknown area "${n}"`); continue }
|
|
252
|
+
mask |= 1 << id
|
|
253
|
+
}
|
|
254
|
+
return mask
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
private masks(opts?: NavQueryOptions): [number, number] {
|
|
258
|
+
return [ opts?.include ? this.flags(opts.include) : FLAGS_ALL, opts?.exclude ? this.flags(opts.exclude) : 0 ]
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Traversal cost of a named area (1 = plain ground; > 1 = avoided when a cheaper way exists). */
|
|
262
|
+
cost(area: string, cost: number): void {
|
|
263
|
+
const id = this.areas[area]
|
|
264
|
+
if (id === undefined) { console.warn(`NavMesh: unknown area "${area}"`); return }
|
|
265
|
+
if (!this._disposed) _creatorNav.setAreaCost(this.id, id, cost)
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** The straight (string-pulled) path from → to. Empty when an endpoint is off the mesh;
|
|
269
|
+
* `.partial` when the target is unreachable (the path ends at the closest polygon). */
|
|
270
|
+
findPath(from: Vec3Like, to: Vec3Like, opts?: NavQueryOptions & { maxCorners?: number }): NavPath {
|
|
271
|
+
const path = [] as unknown as NavPath
|
|
272
|
+
path.partial = false
|
|
273
|
+
if (this._disposed) return path
|
|
274
|
+
const [ inc, exc ] = this.masks(opts)
|
|
275
|
+
const e = opts?.extents
|
|
276
|
+
const max = Math.min(opts?.maxCorners ?? 256, 256)
|
|
277
|
+
const n = _creatorNav.findPath(this.id, cx(from), cy(from), cz(from), cx(to), cy(to), cz(to),
|
|
278
|
+
e ? cx(e) : 0, e ? cy(e) : 0, e ? cz(e) : 0, inc, exc, max, pathScratch)
|
|
279
|
+
const count = Math.abs(n)
|
|
280
|
+
for (let i = 0; i < count; i++) path.push(new Vec3(pathScratch[i * 3]!, pathScratch[i * 3 + 1]!, pathScratch[i * 3 + 2]!))
|
|
281
|
+
path.partial = n < 0
|
|
282
|
+
return path
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** The closest point on the mesh (within `extents` of `p`), or null. */
|
|
286
|
+
nearest(p: Vec3Like, opts?: NavQueryOptions): Vec3 | null {
|
|
287
|
+
if (this._disposed) return null
|
|
288
|
+
const [ inc, exc ] = this.masks(opts)
|
|
289
|
+
const e = opts?.extents
|
|
290
|
+
const ok = _creatorNav.nearest(this.id, cx(p), cy(p), cz(p), e ? cx(e) : 0, e ? cy(e) : 0, e ? cz(e) : 0, inc, exc, scratch)
|
|
291
|
+
return ok ? new Vec3(scratch[0]!, scratch[1]!, scratch[2]!) : null
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Can an agent walk straight from → to? `hit` = a wall in between (at `point`, facing `normal`). */
|
|
295
|
+
raycast(from: Vec3Like, to: Vec3Like, opts?: NavQueryOptions): NavRaycastHit {
|
|
296
|
+
if (this._disposed) return { hit: true, point: new Vec3(cx(from), cy(from), cz(from)), normal: new Vec3(0, 0, 0) }
|
|
297
|
+
const [ inc, exc ] = this.masks(opts)
|
|
298
|
+
const hit = _creatorNav.raycast(this.id, cx(from), cy(from), cz(from), cx(to), cy(to), cz(to), inc, exc, scratch)
|
|
299
|
+
return { hit, point: new Vec3(scratch[0]!, scratch[1]!, scratch[2]!), normal: new Vec3(scratch[3]!, scratch[4]!, scratch[5]!) }
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** A random reachable point — within walking distance `radius` of `center`, or anywhere on the
|
|
303
|
+
* mesh. Deterministic: the sequence depends only on the calls made (a seeded generator). */
|
|
304
|
+
randomPoint(center?: Vec3Like, radius = 0, opts?: NavQueryOptions): Vec3 | null {
|
|
305
|
+
if (this._disposed) return null
|
|
306
|
+
const [ inc, exc ] = this.masks(opts)
|
|
307
|
+
this._seed = (Math.imul(this._seed, 1664525) + 1013904223) >>> 0
|
|
308
|
+
const c = center && radius > 0
|
|
309
|
+
const ok = _creatorNav.randomPoint(this.id, c ? cx(center) : 0, c ? cy(center) : 0, c ? cz(center) : 0, c ? radius : 0, this._seed || 1, inc, exc, scratch)
|
|
310
|
+
return ok ? new Vec3(scratch[0]!, scratch[1]!, scratch[2]!) : null
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Draw the polygon mesh (a flat unlit surface 3 cm above the walkable area). */
|
|
314
|
+
get debug(): boolean { return this._debug.length > 0 }
|
|
315
|
+
set debug(on: boolean) {
|
|
316
|
+
if (on === this.debug || this._disposed) return
|
|
317
|
+
if (!on) { for (const m of this._debug) m.destroy(); this._debug = []; return }
|
|
318
|
+
const tris = _creatorNav.debugTriangles(this.id)
|
|
319
|
+
const material = Material.unlit({ color: "#3b82f6" })
|
|
320
|
+
// Geometry indexes with 16-bit indices: chunk the soup
|
|
321
|
+
const perChunk = 65535 - (65535 % 3)
|
|
322
|
+
for (let start = 0; start < tris.length / 3; start += perChunk) {
|
|
323
|
+
const count = Math.min(perChunk, tris.length / 3 - start)
|
|
324
|
+
const vertices = new Float32Array(count * 3)
|
|
325
|
+
const normals = new Float32Array(count * 3)
|
|
326
|
+
const uv = new Float32Array(count * 2)
|
|
327
|
+
const indices = new Uint16Array(count)
|
|
328
|
+
for (let i = 0; i < count; i++) {
|
|
329
|
+
vertices[i * 3] = tris[(start + i) * 3]!
|
|
330
|
+
vertices[i * 3 + 1] = tris[(start + i) * 3 + 1]! + 0.03
|
|
331
|
+
vertices[i * 3 + 2] = tris[(start + i) * 3 + 2]!
|
|
332
|
+
normals[i * 3 + 1] = 1
|
|
333
|
+
indices[i] = i
|
|
334
|
+
}
|
|
335
|
+
const mesh = new Mesh(new Geometry(vertices, normals, indices, uv), material)
|
|
336
|
+
mesh.name = "navmesh-debug"
|
|
337
|
+
mesh.castShadows = false
|
|
338
|
+
this.scene.add(mesh)
|
|
339
|
+
this._debug.push(mesh)
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** @internal The scene's crowd system (created on the first agent). */
|
|
344
|
+
_crowd(): NavCrowd {
|
|
345
|
+
const existing = this.scene.get(NavCrowd)
|
|
346
|
+
if (existing && existing._mesh === this) return existing
|
|
347
|
+
const crowd = this.scene.system(NavCrowd).navCrowd
|
|
348
|
+
crowd._mesh = this
|
|
349
|
+
return crowd
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Release the host handles (a scene teardown). Agents fall back to inert. */
|
|
353
|
+
dispose(): void {
|
|
354
|
+
if (this._disposed) return
|
|
355
|
+
this._disposed = true
|
|
356
|
+
this.debug = false
|
|
357
|
+
const crowd = this.scene.get(NavCrowd)
|
|
358
|
+
if (crowd && crowd._mesh === this) {
|
|
359
|
+
for (const a of crowd._agents) a._leave()
|
|
360
|
+
this.scene.removeSystem(NavCrowd)
|
|
361
|
+
}
|
|
362
|
+
if (hasNav()) _creatorNav.unload(this.id)
|
|
363
|
+
if (NavMesh.byScene.get(this.scene) === this) NavMesh.byScene.delete(this.scene)
|
|
364
|
+
if (NavMesh.active === this) NavMesh.active = null
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// ---- bake mode ----------------------------------------------------------------------------------
|
|
368
|
+
|
|
369
|
+
private static bake(cfg: BakeConfig, opts: NavMeshLoadOptions): void {
|
|
370
|
+
if (NavMesh.baked) { console.log("[navmesh] a second NavMesh.load — skipped (one bake per run; use --entry per scene)"); return }
|
|
371
|
+
NavMesh.baked = true
|
|
372
|
+
if (!_creator.physicsStaticGeometry) {
|
|
373
|
+
console.error("[navmesh] error: this host cannot dump collision geometry (build the desktop host from packages/desktop, or update: lecodes desktop update)")
|
|
374
|
+
return
|
|
375
|
+
}
|
|
376
|
+
const areaIds = NavMesh.areaIds(opts.areas)
|
|
377
|
+
const ids: number[] = []
|
|
378
|
+
const areas: number[] = []
|
|
379
|
+
for (const [ entity, area ] of NavMesh.overrides) {
|
|
380
|
+
let id: number
|
|
381
|
+
if (typeof area === "string") {
|
|
382
|
+
id = areaIds[area] ?? -1
|
|
383
|
+
if (id < 0) { console.warn(`[navmesh] unknown area "${area}" on entity ${entity} — declare it in the navmesh 'areas'`); continue }
|
|
384
|
+
} else id = area
|
|
385
|
+
ids.push(entity)
|
|
386
|
+
areas.push(id)
|
|
387
|
+
}
|
|
388
|
+
const path = `${cfg.outDir}/${cfg.name ?? "scene"}.navgeo`
|
|
389
|
+
const n = _creator.physicsStaticGeometry(path, Uint32Array.from(ids), Uint8Array.from(areas))
|
|
390
|
+
if (n < 0) { console.error(`[navmesh] error: the geometry dump failed (${path})`); return }
|
|
391
|
+
if (n === 0) { console.error("[navmesh] error: no static collision geometry — agents walk on STATIC Physics bodies (Shape + Physics { motion: 'static' })"); return }
|
|
392
|
+
const agent = { radius: opts.agent?.radius ?? 0.4, height: opts.agent?.height ?? 1.8, climb: opts.agent?.climb ?? 0.4, slope: opts.agent?.slope ?? 50 }
|
|
393
|
+
console.log(`[navmesh] geometry ${n} triangles → ${path}`)
|
|
394
|
+
console.log(`[navmesh] config ${JSON.stringify({ agent, areas: areaIds, costs: opts.areas ?? {}, data: opts.data })}`)
|
|
395
|
+
console.log("[navmesh] done")
|
|
396
|
+
}
|
|
397
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// A ragdoll: the model's skeleton handed to physics. One rigid body per listed bone — a capsule from
|
|
2
|
+
// the bone's origin to the next joint down the chain — joined to its parent part by a swing-twist
|
|
3
|
+
// constraint (a cone + a twist range, or a one-way hinge for knees and elbows). Built once at
|
|
4
|
+
// attach from the pose the model is in (that pose is the joints' neutral for the limits), and
|
|
5
|
+
// switched on and off at will:
|
|
6
|
+
//
|
|
7
|
+
// const rag = hero.aspect(Ragdoll).get(Ragdoll)! // 'humanoid': the parts by bone name
|
|
8
|
+
// rag.activate({ velocity: capsule.controller.velocity }) // drops from its CURRENT pose, keeps its speed
|
|
9
|
+
// …
|
|
10
|
+
// rag.deactivate() // the animator owns the bones again
|
|
11
|
+
//
|
|
12
|
+
// While active the engine writes the bodies' poses onto the bones every frame AFTER the animator, so
|
|
13
|
+
// the listed bones hide whatever plays underneath; bones NOT listed (fingers, toes, the rest of a
|
|
14
|
+
// spine chain between two parts) keep their animated local pose under the ragdolled parents, and
|
|
15
|
+
// anything mounted on a bone (a weapon in the hand) rides along. Raycasts hit the parts and report
|
|
16
|
+
// the bone node, so a shot knows which limb it struck — `impulse(bone, …)` pushes that part.
|
|
17
|
+
//
|
|
18
|
+
// The character CONTROLLER is yours to switch off (`node.removeAspect(CharacterController)`): a
|
|
19
|
+
// capsule left standing would keep the fallen body from settling. `root` (the hips) tells you where
|
|
20
|
+
// the body ended up when it is time to get back up.
|
|
21
|
+
//
|
|
22
|
+
// A fallen body is scenery, not an obstacle: by default (`collide: 'static'`) only the static world
|
|
23
|
+
// and other ragdolls stop it — dynamic bodies, character controllers and vehicles pass through, so it
|
|
24
|
+
// never shoves or blocks anything and the solver never pairs it with them — and once every part has
|
|
25
|
+
// come to rest (`freeze`, or `freezeAfter` seconds at the latest) the parts turn static where they
|
|
26
|
+
// lie: the pose holds, nothing can wake them, the solver skips them. Raycasts hit it either way, and
|
|
27
|
+
// a frozen `'all'` body is an obstacle you can stand on.
|
|
28
|
+
|
|
29
|
+
import { Aspect } from "../core/Aspect"
|
|
30
|
+
import type { FieldMeta } from "../core/fields"
|
|
31
|
+
import { cx, cy, cz, type Vec3Like } from "../math/vec"
|
|
32
|
+
import { Node } from "./Node"
|
|
33
|
+
import { DEFAULT_FRICTION } from "./Physics"
|
|
34
|
+
|
|
35
|
+
export interface RagdollHinge {
|
|
36
|
+
/** The hinge axis in the MODEL's space (its rest pose: +Z forward, +Y up, +X the model's left in
|
|
37
|
+
* glTF). Perpendicular to the bone; the engine drops any component along it. */
|
|
38
|
+
axis: Vec3Like
|
|
39
|
+
/** The bend range about `axis` in degrees, relative to the pose the ragdoll was built in — a knee
|
|
40
|
+
* is `{ axis: [1, 0, 0], min: 0, max: 140 }`: it folds one way only. */
|
|
41
|
+
min: number
|
|
42
|
+
max: number
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface RagdollPart {
|
|
46
|
+
/** The bone the body sits on — its origin is the joint. */
|
|
47
|
+
bone: string
|
|
48
|
+
/** The bone the capsule points at (the next joint down). Omitted = a leaf: `length` along the line
|
|
49
|
+
* from the parent part's origin (a head, a hand, a foot without toes). */
|
|
50
|
+
to?: string
|
|
51
|
+
/** The bone of the part this one hangs from (default: the previous part in the list). The root
|
|
52
|
+
* has none. */
|
|
53
|
+
parent?: string
|
|
54
|
+
/** Capsule radius in metres (default 0.05). */
|
|
55
|
+
radius?: number
|
|
56
|
+
/** Length in metres: a leaf's, or an override of the distance to `to`. */
|
|
57
|
+
length?: number
|
|
58
|
+
/** This part's share of the ragdoll's `mass` (relative weight, default 1). */
|
|
59
|
+
mass?: number
|
|
60
|
+
/** Cone half-angle in degrees the part may swing off its parent (default 30). Ignored with `hinge`. */
|
|
61
|
+
swing?: number
|
|
62
|
+
/** Twist half-angle in degrees about its own axis (default 20). */
|
|
63
|
+
twist?: number
|
|
64
|
+
/** A one-way joint instead of the cone. */
|
|
65
|
+
hinge?: RagdollHinge
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const VERSION = 2
|
|
69
|
+
const HEADER = 12
|
|
70
|
+
const STRIDE = 12
|
|
71
|
+
|
|
72
|
+
// Bone names per humanoid role, tried in order: Mixamo / MotusMan / Unity-style first, then UE-style.
|
|
73
|
+
// `node.bone()` already matches the part after a `:` / `|` prefix (`mixamorig:Hips`).
|
|
74
|
+
const HUMANOID: Record<string, string[]> = {
|
|
75
|
+
hips: [ "Hips", "pelvis", "Pelvis", "hip" ],
|
|
76
|
+
spine: [ "Spine", "spine_01", "spine", "Spine1" ],
|
|
77
|
+
neck: [ "Neck", "neck_01", "neck" ],
|
|
78
|
+
head: [ "Head", "head" ],
|
|
79
|
+
upperArmL: [ "LeftArm", "upperarm_l", "LeftUpperArm", "UpperArm_L", "L_UpperArm" ],
|
|
80
|
+
foreArmL: [ "LeftForeArm", "lowerarm_l", "LeftLowerArm", "LowerArm_L", "L_Forearm" ],
|
|
81
|
+
handL: [ "LeftHand", "hand_l", "Hand_L", "L_Hand" ],
|
|
82
|
+
upLegL: [ "LeftUpLeg", "thigh_l", "LeftUpperLeg", "UpperLeg_L", "L_Thigh" ],
|
|
83
|
+
legL: [ "LeftLeg", "calf_l", "LeftLowerLeg", "LowerLeg_L", "L_Calf" ],
|
|
84
|
+
footL: [ "LeftFoot", "foot_l", "Foot_L", "L_Foot" ],
|
|
85
|
+
toeL: [ "LeftToeBase", "ball_l", "LeftToe", "Toe_L", "L_Toe" ],
|
|
86
|
+
upperArmR: [ "RightArm", "upperarm_r", "RightUpperArm", "UpperArm_R", "R_UpperArm" ],
|
|
87
|
+
foreArmR: [ "RightForeArm", "lowerarm_r", "RightLowerArm", "LowerArm_R", "R_Forearm" ],
|
|
88
|
+
handR: [ "RightHand", "hand_r", "Hand_R", "R_Hand" ],
|
|
89
|
+
upLegR: [ "RightUpLeg", "thigh_r", "RightUpperLeg", "UpperLeg_R", "R_Thigh" ],
|
|
90
|
+
legR: [ "RightLeg", "calf_r", "RightLowerLeg", "LowerLeg_R", "R_Calf" ],
|
|
91
|
+
footR: [ "RightFoot", "foot_r", "Foot_R", "R_Foot" ],
|
|
92
|
+
toeR: [ "RightToeBase", "ball_r", "RightToe", "Toe_R", "R_Toe" ],
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The standard humanoid layout (hips, one spine capsule up to the neck, head, two-segment arms and
|
|
96
|
+
* legs, hands and feet where the rig has them): sizes for a ~1.8 m human, mass shares from body
|
|
97
|
+
* segment tables, knees and elbows as hinges that fold the natural way for a model standing in a
|
|
98
|
+
* T- or A-pose facing +Z. */
|
|
99
|
+
const humanoidParts = (find: (role: string) => string | null): RagdollPart[] => {
|
|
100
|
+
const hips = find("hips"), spine = find("spine"), neck = find("neck"), head = find("head")
|
|
101
|
+
if (!hips) throw new Error("Ragdoll 'humanoid': no hips bone (Hips / pelvis) on this model — list the parts by name")
|
|
102
|
+
const parts: RagdollPart[] = []
|
|
103
|
+
parts.push({ bone: hips, to: spine ?? undefined, length: spine ? 0 : 0.2, radius: 0.12, mass: 15 })
|
|
104
|
+
const torso = spine ?? hips
|
|
105
|
+
if (spine) parts.push({ bone: spine, to: neck ?? head ?? undefined, length: neck || head ? 0 : 0.4, parent: hips, radius: 0.11, mass: 25, swing: 25, twist: 25 })
|
|
106
|
+
if (head) parts.push({ bone: head, parent: torso, radius: 0.1, length: 0.2, mass: 6, swing: 35, twist: 45 })
|
|
107
|
+
for (const side of [ "L", "R" ] as const) {
|
|
108
|
+
const upper = find(`upperArm${side}`), fore = find(`foreArm${side}`), hand = find(`hand${side}`)
|
|
109
|
+
if (upper) parts.push({ bone: upper, to: fore ?? undefined, length: fore ? 0 : 0.3, parent: torso, radius: 0.05, mass: 3, swing: 80, twist: 45 })
|
|
110
|
+
// the elbow: a T-pose arm along ±X folds its hand forward (+Z) — a negative turn about +Y on the
|
|
111
|
+
// left, a positive one on the right
|
|
112
|
+
if (upper && fore) parts.push({ bone: fore, to: hand ?? undefined, length: hand ? 0 : 0.28, parent: upper, radius: 0.04, mass: 2, twist: 30, hinge: { axis: [ 0, 1, 0 ], min: side === "L" ? -140 : 0, max: side === "L" ? 0 : 140 } })
|
|
113
|
+
if (upper && fore && hand) parts.push({ bone: hand, parent: fore, radius: 0.035, length: 0.16, mass: 1, swing: 30, twist: 20 })
|
|
114
|
+
const up = find(`upLeg${side}`), leg = find(`leg${side}`), foot = find(`foot${side}`), toe = find(`toe${side}`)
|
|
115
|
+
if (up) parts.push({ bone: up, to: leg ?? undefined, length: leg ? 0 : 0.45, parent: hips, radius: 0.08, mass: 10, swing: 60, twist: 30 })
|
|
116
|
+
// the knee: the shin (pointing down) swings its foot backward (−Z) for a positive turn about +X
|
|
117
|
+
if (up && leg) parts.push({ bone: leg, to: foot ?? undefined, length: foot ? 0 : 0.42, parent: up, radius: 0.06, mass: 5, twist: 10, hinge: { axis: [ 1, 0, 0 ], min: 0, max: 140 } })
|
|
118
|
+
if (up && leg && foot) parts.push({ bone: foot, to: toe ?? undefined, length: toe ? 0 : 0.2, parent: leg, radius: 0.04, mass: 2, swing: 30, twist: 15 })
|
|
119
|
+
}
|
|
120
|
+
return parts
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export class Ragdoll extends Aspect<"ragdoll", Node> {
|
|
124
|
+
static readonly aspect = "ragdoll"
|
|
125
|
+
|
|
126
|
+
/** The parts: `'humanoid'` (default) finds the standard bones by name; a list places bodies on any
|
|
127
|
+
* bones — parents before children. */
|
|
128
|
+
parts: RagdollPart[] | "humanoid" = "humanoid"
|
|
129
|
+
/** Total mass in kg (default 70), split between the parts by their `mass` shares. */
|
|
130
|
+
mass = 70
|
|
131
|
+
/** Friction of every part (default 0.6 — the physics default). */
|
|
132
|
+
friction = DEFAULT_FRICTION
|
|
133
|
+
/** Linear / angular damping of every part; 0 = Jolt's own 0.05. More angular damping settles a
|
|
134
|
+
* flailing body sooner. */
|
|
135
|
+
linearDamping = 0
|
|
136
|
+
angularDamping = 0
|
|
137
|
+
/** What the parts collide with. `'static'` (default): the static geometry and other such ragdolls
|
|
138
|
+
* only — dynamic bodies, character controllers and vehicles pass through a fallen body, which then
|
|
139
|
+
* never shoves or blocks anything and costs nothing when they meet. `'all'`: a regular dynamic
|
|
140
|
+
* body that bumps into everything (and gets kicked awake by everything). */
|
|
141
|
+
collide: "static" | "all" = "static"
|
|
142
|
+
/** Once every part has come to rest the parts turn static where they lie (default true): the pose
|
|
143
|
+
* holds, nothing can wake a settled body and it costs the solver nothing — `deactivate()` /
|
|
144
|
+
* `activate()` still work (activate makes it dynamic again). */
|
|
145
|
+
freeze = true
|
|
146
|
+
/** Seconds after `activate()` at which the body freezes whatever it is doing — a twitch on a slope
|
|
147
|
+
* or a pile never sleeps on its own. 0 (default) = no cap. */
|
|
148
|
+
freezeAfter = 0
|
|
149
|
+
|
|
150
|
+
static fields: FieldMeta<Ragdoll> = {
|
|
151
|
+
mass: { min: 1, step: 5 },
|
|
152
|
+
friction: { min: 0, max: 2, step: 0.05 },
|
|
153
|
+
linearDamping: { label: "Linear damping", min: 0, max: 5, step: 0.05 },
|
|
154
|
+
angularDamping: { label: "Angular damping", min: 0, max: 5, step: 0.05 },
|
|
155
|
+
collide: { options: [ "static", "all" ] },
|
|
156
|
+
freezeAfter: { label: "Freeze after (s)", min: 0, max: 60, step: 0.5 },
|
|
157
|
+
parts: { hidden: true },
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
private _id = 0
|
|
161
|
+
private _active = false
|
|
162
|
+
private _bones: { name: string; node: Node }[] = []
|
|
163
|
+
|
|
164
|
+
onAttach(): void {
|
|
165
|
+
if (!_creator.physicsHasSupport || !_creator.physicsHasSupport()) return
|
|
166
|
+
if (!_creator.ragdollCreate) {
|
|
167
|
+
console.warn("Ragdoll needs a newer host (no ragdollCreate) — the body will not fall")
|
|
168
|
+
return
|
|
169
|
+
}
|
|
170
|
+
const find = (role: string): string | null => {
|
|
171
|
+
for (const name of HUMANOID[role] ?? []) if (this.node.bone(name)) return name
|
|
172
|
+
return null
|
|
173
|
+
}
|
|
174
|
+
const parts = this.parts === "humanoid" ? humanoidParts(find) : this.parts
|
|
175
|
+
if (parts.length === 0) throw new Error("Ragdoll: no parts")
|
|
176
|
+
|
|
177
|
+
const n = parts.length
|
|
178
|
+
const bones = new Uint32Array(n * 2)
|
|
179
|
+
const s = new Float32Array(HEADER + n * STRIDE)
|
|
180
|
+
s[0] = VERSION; s[1] = n; s[2] = STRIDE; s[3] = this.friction; s[4] = this.linearDamping; s[5] = this.angularDamping
|
|
181
|
+
s[6] = this.collide === "all" ? 0 : 1; s[7] = this.freeze ? 1 : 0; s[8] = Math.max(0, this.freezeAfter)
|
|
182
|
+
let shares = 0
|
|
183
|
+
for (const p of parts) shares += p.mass ?? 1
|
|
184
|
+
this._bones = []
|
|
185
|
+
for (let i = 0; i < n; i++) {
|
|
186
|
+
const p = parts[i]!
|
|
187
|
+
const bone = this.node.bone(p.bone)
|
|
188
|
+
if (!bone) throw new Error(`Ragdoll: no bone '${p.bone}' on '${this.node.name}'`)
|
|
189
|
+
const to = p.to ? this.node.bone(p.to) : null
|
|
190
|
+
if (p.to && !to) throw new Error(`Ragdoll: no bone '${p.to}' (the 'to' of '${p.bone}') on '${this.node.name}'`)
|
|
191
|
+
let parent = -1
|
|
192
|
+
if (i > 0) {
|
|
193
|
+
parent = p.parent ? parts.findIndex((q, j) => j < i && q.bone === p.parent) : i - 1
|
|
194
|
+
if (parent < 0) throw new Error(`Ragdoll: the parent '${p.parent}' of '${p.bone}' must be listed before it`)
|
|
195
|
+
}
|
|
196
|
+
bones[i * 2] = bone.id
|
|
197
|
+
bones[i * 2 + 1] = to ? to.id : 0
|
|
198
|
+
const o = HEADER + i * STRIDE
|
|
199
|
+
s[o] = parent
|
|
200
|
+
s[o + 1] = p.radius ?? 0.05
|
|
201
|
+
s[o + 2] = p.length ?? 0
|
|
202
|
+
s[o + 3] = this.mass * (p.mass ?? 1) / shares
|
|
203
|
+
s[o + 4] = p.swing ?? 30
|
|
204
|
+
s[o + 5] = p.twist ?? 20
|
|
205
|
+
if (p.hinge) {
|
|
206
|
+
s[o + 6] = 1
|
|
207
|
+
s[o + 7] = cx(p.hinge.axis); s[o + 8] = cy(p.hinge.axis); s[o + 9] = cz(p.hinge.axis)
|
|
208
|
+
s[o + 10] = p.hinge.min; s[o + 11] = p.hinge.max
|
|
209
|
+
}
|
|
210
|
+
this._bones.push({ name: p.bone, node: bone })
|
|
211
|
+
}
|
|
212
|
+
this._id = _creator.ragdollCreate(this.node.id, bones, s)
|
|
213
|
+
if (!this._id) console.warn(`Ragdoll: the host refused the parts on '${this.node.name}'`)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
onDetach(): void {
|
|
217
|
+
if (this._id) {
|
|
218
|
+
if (this._active) _creator.ragdollDeactivate!(this._id)
|
|
219
|
+
_creator.ragdollDestroy!(this._id)
|
|
220
|
+
this._id = 0
|
|
221
|
+
}
|
|
222
|
+
this._active = false
|
|
223
|
+
this._bones = []
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Hand the bones to physics from the pose they are in right now. `velocity` (world m/s) is given
|
|
227
|
+
* to every part — pass the character's, so a running body keeps travelling. */
|
|
228
|
+
activate(opts: { velocity?: Vec3Like } = {}): boolean {
|
|
229
|
+
if (!this._id) return false
|
|
230
|
+
const v = opts.velocity ?? [ 0, 0, 0 ]
|
|
231
|
+
this._active = _creator.ragdollActivate!(this._id, cx(v), cy(v), cz(v))
|
|
232
|
+
return this._active
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Take the bones back: the animator's pose shows again from the next frame. */
|
|
236
|
+
deactivate(): void {
|
|
237
|
+
if (!this._id || !this._active) return
|
|
238
|
+
_creator.ragdollDeactivate!(this._id)
|
|
239
|
+
this._active = false
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Physics owns the bones right now. */
|
|
243
|
+
get active(): boolean { return this._active }
|
|
244
|
+
|
|
245
|
+
/** Active and every part asleep (or frozen) — the body has come to rest. */
|
|
246
|
+
get settled(): boolean {
|
|
247
|
+
return this._active && !!this._id && !_creator.ragdollActive!(this._id)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** The root part's bone (the hips): where the body is. */
|
|
251
|
+
get root(): Node | null { return this._bones[0]?.node ?? null }
|
|
252
|
+
|
|
253
|
+
/** The bones that carry a part, in order. */
|
|
254
|
+
get bones(): string[] { return this._bones.map((b) => b.name) }
|
|
255
|
+
|
|
256
|
+
/** The rigid-body id of a part (0 if none) — for the plain body calls. */
|
|
257
|
+
bodyOf(bone: string): number {
|
|
258
|
+
const i = this._bones.findIndex((b) => b.name === bone)
|
|
259
|
+
return i < 0 || !this._id ? 0 : _creator.ragdollBodyId!(this._id, i)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Push one part: an impulse in N·s, at a world point (a hit) or through its centre. Wakes the body. */
|
|
263
|
+
impulse(bone: string, v: Vec3Like, at?: Vec3Like): boolean {
|
|
264
|
+
const id = this.bodyOf(bone)
|
|
265
|
+
if (!id) return false
|
|
266
|
+
if (at && _creator.physicsApplyImpulseAt) _creator.physicsApplyImpulseAt(id, cx(v), cy(v), cz(v), cx(at), cy(at), cz(at))
|
|
267
|
+
else _creator.physicsApplyImpulse(id, cx(v), cy(v), cz(v))
|
|
268
|
+
return true
|
|
269
|
+
}
|
|
270
|
+
}
|