@bendyline/molen-ambient 0.0.3

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.
@@ -0,0 +1,922 @@
1
+ import { d as registerAmbientSchema, r as AmbientAgent } from "./components-CupqU6fR.mjs";
2
+ import { Transform, componentHandle } from "@bendyline/molen-kernel/world";
3
+ import { createVehicleVisual, vehicleProxyGeometry, vehicleProxyMaterial } from "@bendyline/molen-client/vehicles";
4
+ import * as THREE from "three";
5
+ import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
6
+ import { FigureGeometryCache, applyPose, evaluatePose, figureBodyToSkinnedMesh, figureSeed, resolveFigureDescriptor, strideRateFor } from "@bendyline/molen-figures/client";
7
+ import { createAircraftVisual } from "@bendyline/molen-client/aircraft";
8
+ //#region src/client/proxies.ts
9
+ /**
10
+ * Proxy shapes for ambient vehicles, built from dimensions alone so traffic renders with no
11
+ * content: the parked-car shape for cars, a windowed box for buses and rail cars, and a simple
12
+ * airliner. Bodies are white so `instanceColor` paints them; glass and tyres stay dark.
13
+ */
14
+ const cache = /* @__PURE__ */ new Map();
15
+ function box(x, y, z, width, height, length, color) {
16
+ const geometry = new THREE.BoxGeometry(width, height, length).translate(x, y, z).toNonIndexed();
17
+ geometry.deleteAttribute("uv");
18
+ const tint = new THREE.Color(color);
19
+ const count = geometry.getAttribute("position").count;
20
+ const colors = new Float32Array(count * 3);
21
+ for (let i = 0; i < count; i++) {
22
+ colors[i * 3] = tint.r;
23
+ colors[i * 3 + 1] = tint.g;
24
+ colors[i * 3 + 2] = tint.b;
25
+ }
26
+ geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
27
+ return geometry;
28
+ }
29
+ function merged(parts) {
30
+ const geometry = mergeGeometries(parts);
31
+ for (const part of parts) part.dispose();
32
+ geometry.computeBoundingBox();
33
+ geometry.computeBoundingSphere();
34
+ return geometry;
35
+ }
36
+ const GLASS = "#3d4d57";
37
+ const DARK = "#20242a";
38
+ const WHITE = "#ffffff";
39
+ function busGeometry({ length, width, height }) {
40
+ const parts = [
41
+ box(0, height * .12 + .35, 0, width, height * .24, length, WHITE),
42
+ box(0, height * .52 + .1, 0, width * 1.005, height * .42, length * .94, GLASS),
43
+ box(0, height * .9, 0, width, height * .16, length, WHITE)
44
+ ];
45
+ for (const z of [-length * .32, length * .3]) parts.push(box(0, .45, z, width * 1.01, .9, 1, DARK));
46
+ return merged(parts);
47
+ }
48
+ function railGeometry({ length, width, height }) {
49
+ const parts = [
50
+ box(0, .95 + height * .2, 0, width, height * .4, length, WHITE),
51
+ box(0, .95 + height * .52, 0, width * 1.005, height * .26, length * .97, GLASS),
52
+ box(0, .95 + height * .73, 0, width, height * .16, length, WHITE),
53
+ box(0, .95 + height * .83, 0, width * .5, .08, length * .2, DARK)
54
+ ];
55
+ for (const z of [-length * .36, length * .36]) parts.push(box(0, .5, z, width * .8, .9, 2.6, DARK));
56
+ return merged(parts);
57
+ }
58
+ function aircraftGeometry({ length, width }) {
59
+ const fuselage = length * .1;
60
+ const parts = [
61
+ box(0, 0, 0, fuselage, fuselage, length, WHITE),
62
+ box(0, fuselage * .05, length * .02, width, fuselage * .12, length * .12, WHITE),
63
+ box(0, fuselage * .2, -length * .44, width * .32, fuselage * .1, length * .07, WHITE),
64
+ box(0, fuselage * 1.1, -length * .43, fuselage * .12, fuselage * 1.6, length * .09, WHITE),
65
+ box(0, fuselage * .18, length * .44, fuselage * .72, fuselage * .3, length * .05, GLASS)
66
+ ];
67
+ for (const x of [-width * .17, width * .17]) parts.push(box(x, -fuselage * .45, length * .07, fuselage * .45, fuselage * .45, length * .09, "#c9ccd0"));
68
+ return merged(parts);
69
+ }
70
+ /** The shape to draw for an agent kind and its dimensions. */
71
+ function proxyShapeFor(kind, length) {
72
+ if (kind === "train") return "rail";
73
+ if (kind === "aircraft") return "aircraft";
74
+ return length > 7.5 ? "bus" : "car";
75
+ }
76
+ /** Default body height for a proxy when the type gives none. */
77
+ function proxyHeight(shape, length, width, type) {
78
+ if (shape === "bus") return 3.1;
79
+ if (shape === "rail") return 3.6;
80
+ if (shape === "aircraft") return length * .25;
81
+ if (/van/.test(type) || width >= 1.98) return 2;
82
+ if (/suv|pickup/.test(type)) return 1.75;
83
+ return 1.45;
84
+ }
85
+ /** Cached geometry for a shape at given dimensions (rounded to 10 cm). Never dispose it. */
86
+ function proxyGeometry(shape, dims) {
87
+ const d = {
88
+ length: Math.round(dims.length * 10) / 10,
89
+ width: Math.round(dims.width * 10) / 10,
90
+ height: Math.round(dims.height * 10) / 10
91
+ };
92
+ const key = `${shape}:${d.length}:${d.width}:${d.height}`;
93
+ let geometry = cache.get(key);
94
+ if (geometry !== void 0) return geometry;
95
+ if (shape === "car") geometry = vehicleProxyGeometry({
96
+ ...d,
97
+ wheelbase: d.length * .6,
98
+ wheelTrack: d.width * .84,
99
+ wheelRadius: Math.min(.5, Math.max(.28, d.length * .068))
100
+ });
101
+ else if (shape === "bus") geometry = busGeometry(d);
102
+ else if (shape === "rail") geometry = railGeometry(d);
103
+ else geometry = aircraftGeometry(d);
104
+ cache.set(key, geometry);
105
+ return geometry;
106
+ }
107
+ /** The key `proxyGeometry` caches under (one instanced mesh per key). */
108
+ function proxyKey(shape, dims) {
109
+ return `${shape}:${Math.round(dims.length * 10) / 10}:${Math.round(dims.width * 10) / 10}:${Math.round(dims.height * 10) / 10}`;
110
+ }
111
+ //#endregion
112
+ //#region src/client/batches.ts
113
+ /**
114
+ * Instanced proxies: one `InstancedMesh` per proxy shape and size, refilled every frame from the
115
+ * live agents. Matrices are relative to an anchor near the camera (float32 instance matrices lose
116
+ * precision at Web Mercator magnitudes); the anchor group sits at the anchor in absolute
117
+ * coordinates, so the renderer's floating origin never needs a re-upload.
118
+ */
119
+ const ANCHOR_STEP = 250;
120
+ var ProxyBatches = class {
121
+ prepare;
122
+ initialCapacity;
123
+ group = new THREE.Group();
124
+ batches = /* @__PURE__ */ new Map();
125
+ anchor = new THREE.Vector3(NaN, 0, NaN);
126
+ matrix = new THREE.Matrix4();
127
+ position = new THREE.Vector3();
128
+ quaternion = new THREE.Quaternion();
129
+ scale = new THREE.Vector3();
130
+ constructor(prepare, initialCapacity = 64) {
131
+ this.prepare = prepare;
132
+ this.initialCapacity = initialCapacity;
133
+ this.group.name = "ambient:proxies";
134
+ }
135
+ /** Start a frame: keep the anchor within a few hundred metres of the camera. */
136
+ begin(camera) {
137
+ if (!Number.isFinite(this.anchor.x) || Math.abs(camera[0] - this.anchor.x) > ANCHOR_STEP || Math.abs(camera[2] - this.anchor.z) > ANCHOR_STEP) {
138
+ this.anchor.set(Math.round(camera[0] / ANCHOR_STEP) * ANCHOR_STEP, 0, Math.round(camera[2] / ANCHOR_STEP) * ANCHOR_STEP);
139
+ this.group.position.copy(this.anchor);
140
+ }
141
+ for (const batch of this.batches.values()) batch.count = 0;
142
+ }
143
+ add(instance) {
144
+ const key = proxyKey(instance.shape, instance.dims);
145
+ let batch = this.batches.get(key);
146
+ if (batch === void 0 || batch.count >= batch.mesh.instanceMatrix.count) batch = this.grow(key, instance, batch);
147
+ this.position.set(instance.pos[0] - this.anchor.x, instance.pos[1] - this.anchor.y, instance.pos[2] - this.anchor.z);
148
+ this.quaternion.set(instance.rot[0], instance.rot[1], instance.rot[2], instance.rot[3]);
149
+ this.scale.setScalar(instance.scale);
150
+ this.matrix.compose(this.position, this.quaternion, this.scale);
151
+ batch.mesh.setMatrixAt(batch.count, this.matrix);
152
+ batch.mesh.setColorAt(batch.count, instance.color);
153
+ batch.count++;
154
+ }
155
+ /** Finish a frame: upload what changed and cull empty batches from drawing. */
156
+ end() {
157
+ let total = 0;
158
+ for (const batch of this.batches.values()) {
159
+ const mesh = batch.mesh;
160
+ mesh.count = batch.count;
161
+ mesh.visible = batch.count > 0;
162
+ total += batch.count;
163
+ if (batch.count === 0) continue;
164
+ mesh.instanceMatrix.clearUpdateRanges();
165
+ mesh.instanceMatrix.addUpdateRange(0, batch.count * 16);
166
+ mesh.instanceMatrix.needsUpdate = true;
167
+ if (mesh.instanceColor !== null) {
168
+ mesh.instanceColor.clearUpdateRanges();
169
+ mesh.instanceColor.addUpdateRange(0, batch.count * 3);
170
+ mesh.instanceColor.needsUpdate = true;
171
+ }
172
+ mesh.computeBoundingSphere();
173
+ }
174
+ return total;
175
+ }
176
+ grow(key, instance, previous) {
177
+ const capacity = previous === void 0 ? this.initialCapacity : previous.mesh.instanceMatrix.count * 2;
178
+ const geometry = proxyGeometry(instance.shape, instance.dims);
179
+ const mesh = new THREE.InstancedMesh(geometry, vehicleProxyMaterial, capacity);
180
+ mesh.name = `ambient:${key}`;
181
+ mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
182
+ mesh.setColorAt(0, new THREE.Color(1, 1, 1));
183
+ mesh.instanceColor?.setUsage(THREE.DynamicDrawUsage);
184
+ mesh.castShadow = false;
185
+ mesh.receiveShadow = true;
186
+ mesh.userData.walkIgnore = true;
187
+ mesh.count = 0;
188
+ const batch = {
189
+ mesh,
190
+ count: previous?.count ?? 0
191
+ };
192
+ if (previous !== void 0) {
193
+ for (let i = 0; i < previous.count; i++) {
194
+ previous.mesh.getMatrixAt(i, this.matrix);
195
+ mesh.setMatrixAt(i, this.matrix);
196
+ const color = new THREE.Color();
197
+ previous.mesh.getColorAt(i, color);
198
+ mesh.setColorAt(i, color);
199
+ }
200
+ previous.mesh.removeFromParent();
201
+ previous.mesh.dispose();
202
+ }
203
+ this.group.add(mesh);
204
+ this.batches.set(key, batch);
205
+ this.prepare?.(mesh);
206
+ return batch;
207
+ }
208
+ /** Number of instanced meshes (draw calls when all are populated). */
209
+ get meshCount() {
210
+ return this.batches.size;
211
+ }
212
+ dispose() {
213
+ for (const batch of this.batches.values()) {
214
+ batch.mesh.removeFromParent();
215
+ batch.mesh.dispose();
216
+ }
217
+ this.batches.clear();
218
+ this.group.removeFromParent();
219
+ }
220
+ };
221
+ //#endregion
222
+ //#region src/client/figures.ts
223
+ /**
224
+ * Pedestrians as procedural figures, posed without the kernel figures systems (so a main-thread
225
+ * host never loads the script host): gait comes from each agent's speed and the distance it has
226
+ * walked, which keeps feet planted across lane changes. Meshes are pooled per body key, detail
227
+ * tiers follow distance with hysteresis, and pose evaluation is budgeted per frame.
228
+ */
229
+ var AmbientFigures = class {
230
+ prepare;
231
+ group = new THREE.Group();
232
+ cache = new FigureGeometryCache();
233
+ material = new THREE.MeshStandardMaterial({
234
+ vertexColors: true,
235
+ roughness: .75,
236
+ metalness: 0
237
+ });
238
+ active = /* @__PURE__ */ new Map();
239
+ pool = /* @__PURE__ */ new Map();
240
+ descriptors = /* @__PURE__ */ new WeakMap();
241
+ budget = {
242
+ skinned: 32,
243
+ radius: 120,
244
+ posesPerFrame: 20
245
+ };
246
+ cursor = 0;
247
+ frame = 0;
248
+ constructor(prepare) {
249
+ this.prepare = prepare;
250
+ this.group.name = "ambient:figures";
251
+ }
252
+ setBudget(budget) {
253
+ this.budget = {
254
+ ...this.budget,
255
+ ...budget
256
+ };
257
+ }
258
+ get count() {
259
+ return this.active.size;
260
+ }
261
+ tierFor(distance, current) {
262
+ const r = this.budget.radius;
263
+ const h = current === void 0 ? 1 : 1.1;
264
+ if (distance > r * 1.25 * h) return void 0;
265
+ const medium = r * .35;
266
+ if (current === 0) return distance > medium * 1.1 ? distance > r * 1.1 ? 2 : 1 : 0;
267
+ if (current === 1) return distance > r * 1.1 ? 2 : distance < medium * .9 ? 0 : 1;
268
+ if (current === 2) return distance < r * .9 ? distance < medium * .9 ? 0 : 1 : 2;
269
+ return distance < medium ? 0 : distance < r ? 1 : 2;
270
+ }
271
+ acquire(descriptor, tier) {
272
+ const cached = this.cache.acquire(descriptor, tier);
273
+ const pooled = this.pool.get(cached.key)?.pop();
274
+ if (pooled !== void 0) {
275
+ this.pooled--;
276
+ this.cache.release(cached.key);
277
+ pooled.root.visible = true;
278
+ return {
279
+ key: cached.key,
280
+ mesh: pooled
281
+ };
282
+ }
283
+ const mesh = figureBodyToSkinnedMesh(cached.body, cached.geometry, this.material);
284
+ mesh.mesh.castShadow = tier === 0;
285
+ mesh.mesh.receiveShadow = true;
286
+ mesh.root.traverse((object) => {
287
+ object.userData.walkIgnore = true;
288
+ });
289
+ this.group.add(mesh.root);
290
+ this.prepare?.(mesh.root);
291
+ return {
292
+ key: cached.key,
293
+ mesh
294
+ };
295
+ }
296
+ pooled = 0;
297
+ releaseMesh(key, mesh) {
298
+ mesh.root.visible = false;
299
+ const list = this.pool.get(key) ?? [];
300
+ if (list.length >= 4 || this.pooled >= 96) {
301
+ mesh.dispose();
302
+ this.cache.release(key);
303
+ return;
304
+ }
305
+ list.push(mesh);
306
+ this.pool.set(key, list);
307
+ this.pooled++;
308
+ }
309
+ /** Update every walker for this frame. */
310
+ update(walkers, camera, tick, tickRate) {
311
+ this.frame++;
312
+ const ranked = walkers.filter((w) => !w.hidden).map((w) => ({
313
+ w,
314
+ distance: Math.hypot(w.pos[0] - camera[0], w.pos[1] - camera[1], w.pos[2] - camera[2])
315
+ })).sort((a, b) => a.distance - b.distance || (a.w.id < b.w.id ? -1 : 1));
316
+ let skinned = 0;
317
+ for (const { w, distance } of ranked) {
318
+ const entry = this.active.get(w.id);
319
+ let tier = this.tierFor(distance, entry?.tier);
320
+ if (tier !== void 0 && tier < 2) if (skinned >= this.budget.skinned) tier = 2;
321
+ else skinned++;
322
+ if (tier === void 0) {
323
+ if (entry !== void 0) {
324
+ this.releaseMesh(entry.key, entry.mesh);
325
+ this.active.delete(w.id);
326
+ }
327
+ continue;
328
+ }
329
+ let current = entry;
330
+ if (current === void 0 || current.tier !== tier) {
331
+ let descriptor = this.descriptors.get(w.figure);
332
+ if (descriptor === void 0) {
333
+ try {
334
+ descriptor = resolveFigureDescriptor(w.figure);
335
+ } catch {
336
+ continue;
337
+ }
338
+ this.descriptors.set(w.figure, descriptor);
339
+ }
340
+ if (current !== void 0) this.releaseMesh(current.key, current.mesh);
341
+ const { key, mesh } = this.acquire(descriptor, tier);
342
+ current = {
343
+ descriptor,
344
+ rig: this.cache.rigFor(descriptor),
345
+ seed: figureSeed(descriptor.seed, w.id),
346
+ tier,
347
+ key,
348
+ mesh,
349
+ pose: void 0,
350
+ walked: current?.walked ?? 0,
351
+ last: current?.last,
352
+ distance,
353
+ seen: this.frame
354
+ };
355
+ this.active.set(w.id, current);
356
+ }
357
+ current.distance = distance;
358
+ current.seen = this.frame;
359
+ if (current.last !== void 0) current.walked += Math.hypot(w.pos[0] - current.last[0], w.pos[2] - current.last[1]);
360
+ current.last = [w.pos[0], w.pos[2]];
361
+ current.mesh.root.position.set(w.pos[0], w.pos[1], w.pos[2]);
362
+ current.mesh.root.quaternion.set(w.rot[0], w.rot[1], w.rot[2], w.rot[3]);
363
+ }
364
+ for (const [id, entry] of this.active) if (entry.seen !== this.frame) {
365
+ this.releaseMesh(entry.key, entry.mesh);
366
+ this.active.delete(id);
367
+ }
368
+ this.pose(walkers, tick, tickRate);
369
+ }
370
+ pose(walkers, tick, tickRate) {
371
+ const byId = new Map(walkers.map((w) => [w.id, w]));
372
+ const animated = [...this.active.entries()].filter(([, e]) => e.mesh.bones.length > 0).sort((a, b) => a[1].distance - b[1].distance);
373
+ const budget = this.budget.posesPerFrame;
374
+ const nearest = Math.min(animated.length, Math.ceil(budget / 2));
375
+ const chosen = animated.slice(0, nearest);
376
+ const rest = animated.slice(nearest);
377
+ for (let i = 0; i < budget - nearest && rest.length > 0 && i < rest.length; i++) chosen.push(rest[(this.cursor + i) % rest.length]);
378
+ if (rest.length > 0) this.cursor = (this.cursor + budget - nearest) % rest.length;
379
+ for (const [id, entry] of chosen) {
380
+ const walker = byId.get(id);
381
+ if (walker === void 0) continue;
382
+ const moving = walker.speed > .05;
383
+ const strideRate = moving ? strideRateFor(walker.speed, entry.rig.legLength) : 0;
384
+ const stride = strideRate > 0 ? walker.speed / strideRate : 1;
385
+ const state = {
386
+ mode: moving ? "walk" : "idle",
387
+ speed: walker.speed,
388
+ strideRate,
389
+ phaseAt: moving ? entry.walked / stride % 1 : 0,
390
+ phaseAtTick: tick,
391
+ modeAtTick: walker.since
392
+ };
393
+ entry.pose = evaluatePose(entry.rig, state, tick, {
394
+ tickRate,
395
+ seed: entry.seed
396
+ }, entry.pose);
397
+ applyPose(entry.pose, entry.mesh.bones);
398
+ }
399
+ }
400
+ dispose() {
401
+ for (const entry of this.active.values()) entry.mesh.dispose();
402
+ for (const list of this.pool.values()) for (const mesh of list) mesh.dispose();
403
+ this.active.clear();
404
+ this.pool.clear();
405
+ this.cache.dispose();
406
+ this.material.dispose();
407
+ this.group.removeFromParent();
408
+ }
409
+ };
410
+ //#endregion
411
+ //#region src/client/kind.ts
412
+ var VehicleHandle = class {
413
+ id;
414
+ ctx;
415
+ material;
416
+ options;
417
+ object = new THREE.Group();
418
+ mesh;
419
+ agentRef;
420
+ shapeKey = "";
421
+ constructor(id, ctx, material, options) {
422
+ this.id = id;
423
+ this.ctx = ctx;
424
+ this.material = material;
425
+ this.options = options;
426
+ this.refresh();
427
+ }
428
+ refresh() {
429
+ const agent = this.ctx.mirror?.peek(this.id, "ambientAgent");
430
+ if (agent === this.agentRef) return;
431
+ this.agentRef = agent;
432
+ if (agent === void 0) return;
433
+ this.object.visible = agent.hidden !== true;
434
+ const shape = proxyShapeFor(agent.kind, agent.length);
435
+ const height = this.options.heights?.[agent.type] ?? proxyHeight(shape, agent.length, agent.width, agent.type);
436
+ const key = `${shape}:${agent.length}:${agent.width}:${height}:${agent.color ?? ""}`;
437
+ if (key === this.shapeKey) return;
438
+ this.shapeKey = key;
439
+ this.mesh?.removeFromParent();
440
+ this.mesh = new THREE.Mesh(proxyGeometry(shape, {
441
+ length: agent.length,
442
+ width: agent.width,
443
+ height
444
+ }), this.material(agent.color ?? "#d8d8d4"));
445
+ this.mesh.castShadow = true;
446
+ this.mesh.receiveShadow = true;
447
+ this.mesh.userData.walkIgnore = true;
448
+ this.object.add(this.mesh);
449
+ }
450
+ update(_renderable) {
451
+ this.refresh();
452
+ }
453
+ setTick() {
454
+ this.refresh();
455
+ }
456
+ dispose() {
457
+ this.mesh?.removeFromParent();
458
+ }
459
+ };
460
+ /** The `ambient-vehicle` renderable kind (proxy meshes) for Worker-hosted scenes. */
461
+ function ambientVehicleKind(options = {}) {
462
+ const materials = /* @__PURE__ */ new Map();
463
+ const material = (color) => {
464
+ let m = materials.get(color);
465
+ if (m === void 0) {
466
+ m = new THREE.MeshStandardMaterial({
467
+ vertexColors: true,
468
+ color,
469
+ roughness: .55,
470
+ metalness: .12
471
+ });
472
+ materials.set(color, m);
473
+ }
474
+ return m;
475
+ };
476
+ return {
477
+ kind: "ambient-vehicle",
478
+ identity: (renderable) => renderable.ref ?? "",
479
+ create: (id, _renderable, ctx) => new VehicleHandle(id, ctx, material, options),
480
+ dispose: () => {
481
+ for (const m of materials.values()) m.dispose();
482
+ materials.clear();
483
+ }
484
+ };
485
+ }
486
+ //#endregion
487
+ //#region src/client/aircraft.ts
488
+ /**
489
+ * Aircraft overhead: content models (propellers or fans turning) when the host supplies them,
490
+ * otherwise instanced proxies drawn by the vehicle batches.
491
+ */
492
+ const INPUT = {
493
+ power: .8,
494
+ pitch: 0,
495
+ roll: 0,
496
+ yaw: 0,
497
+ brake: false,
498
+ engine: true,
499
+ gear: false,
500
+ flaps: false
501
+ };
502
+ var AmbientAircraft = class {
503
+ models;
504
+ parent;
505
+ prepare;
506
+ active = /* @__PURE__ */ new Map();
507
+ loading = /* @__PURE__ */ new Set();
508
+ missing = /* @__PURE__ */ new Set();
509
+ disposed = false;
510
+ constructor(models, parent, prepare) {
511
+ this.models = models;
512
+ this.parent = parent;
513
+ this.prepare = prepare;
514
+ }
515
+ /** Whether a type draws as a model (otherwise the caller draws a proxy). */
516
+ modelled(id) {
517
+ return this.active.has(id);
518
+ }
519
+ /** Keep models for live aircraft; returns ids that still need a proxy this frame. */
520
+ sync(live, dt) {
521
+ const seen = /* @__PURE__ */ new Set();
522
+ for (const plane of live) {
523
+ seen.add(plane.id);
524
+ const entry = this.active.get(plane.id);
525
+ if (entry === void 0) {
526
+ if (!this.missing.has(plane.type) && !this.loading.has(plane.id)) this.load(plane.id, plane.type);
527
+ continue;
528
+ }
529
+ entry.rotor = (entry.rotor + dt * 40) % (Math.PI * 2);
530
+ const object = entry.visual.object;
531
+ object.position.set(plane.pos[0] ?? 0, plane.pos[1] ?? 0, plane.pos[2] ?? 0);
532
+ object.quaternion.set(plane.rot[0] ?? 0, plane.rot[1] ?? 0, plane.rot[2] ?? 0, plane.rot[3] ?? 1);
533
+ entry.visual.update({
534
+ rotorAngle: entry.rotor,
535
+ airspeed: plane.speed,
536
+ altitudeAGL: 500,
537
+ yaw: 0,
538
+ pitch: 0,
539
+ roll: 0,
540
+ rpm: 2400,
541
+ verticalSpeed: 0
542
+ }, {
543
+ ...INPUT,
544
+ gear: plane.descending,
545
+ flaps: plane.descending
546
+ }, plane.pos[1] ?? 0);
547
+ }
548
+ for (const [id, entry] of this.active) if (!seen.has(id)) {
549
+ entry.visual.object.removeFromParent();
550
+ entry.visual.dispose();
551
+ this.active.delete(id);
552
+ }
553
+ }
554
+ async load(id, type) {
555
+ const spec = this.models.aircraft(type);
556
+ if (spec === void 0) {
557
+ this.missing.add(type);
558
+ return;
559
+ }
560
+ this.loading.add(id);
561
+ try {
562
+ const model = await this.models.load(type);
563
+ if (model === void 0) {
564
+ this.missing.add(type);
565
+ return;
566
+ }
567
+ if (this.disposed) return;
568
+ const visual = createAircraftVisual(model, spec);
569
+ visual.object.traverse((object) => {
570
+ object.userData.walkIgnore = true;
571
+ object.castShadow = false;
572
+ });
573
+ this.parent.add(visual.object);
574
+ await this.prepare?.(visual.object);
575
+ if (this.disposed) {
576
+ visual.dispose();
577
+ return;
578
+ }
579
+ this.active.set(id, {
580
+ visual,
581
+ rotor: 0
582
+ });
583
+ } catch {
584
+ this.missing.add(type);
585
+ } finally {
586
+ this.loading.delete(id);
587
+ }
588
+ }
589
+ get count() {
590
+ return this.active.size;
591
+ }
592
+ dispose() {
593
+ this.disposed = true;
594
+ for (const entry of this.active.values()) {
595
+ entry.visual.object.removeFromParent();
596
+ entry.visual.dispose();
597
+ }
598
+ this.active.clear();
599
+ }
600
+ };
601
+ //#endregion
602
+ //#region src/client/detail.ts
603
+ /**
604
+ * Full models for the nearest ambient cars. A few cars near the camera swap their proxy for the
605
+ * content model (wheels turning and steering), from a pool per type so a spawn never builds new
606
+ * GPU objects once the pool is warm. Farther cars stay instanced proxies.
607
+ */
608
+ var VehicleDetail = class {
609
+ options;
610
+ group = new THREE.Group();
611
+ active = /* @__PURE__ */ new Map();
612
+ idle = /* @__PURE__ */ new Map();
613
+ loading = /* @__PURE__ */ new Set();
614
+ missing = /* @__PURE__ */ new Set();
615
+ max = 8;
616
+ disposed = false;
617
+ constructor(options) {
618
+ this.options = options;
619
+ this.group.name = "ambient:detail";
620
+ options.parent.add(this.group);
621
+ }
622
+ setMax(max) {
623
+ this.max = Math.max(0, max);
624
+ }
625
+ has(id) {
626
+ return this.active.has(id);
627
+ }
628
+ get count() {
629
+ return this.active.size;
630
+ }
631
+ /** Choose which cars get full models (call a few times a second). */
632
+ select(candidates, exists) {
633
+ const near = this.options.near ?? 45;
634
+ const far = this.options.far ?? 65;
635
+ const wanted = candidates.filter((c) => c.distance < (this.active.has(c.id) ? far : near) && !this.missing.has(c.type)).sort((a, b) => a.distance - b.distance || (a.id < b.id ? -1 : 1)).slice(0, this.max);
636
+ const keep = new Set(wanted.map((c) => c.id));
637
+ for (const [id, entry] of this.active) if (!keep.has(id) || !exists(id)) {
638
+ entry.visual.object.visible = false;
639
+ this.active.delete(id);
640
+ const pool = this.idle.get(entry.type) ?? [];
641
+ pool.push(entry.visual);
642
+ this.idle.set(entry.type, pool);
643
+ }
644
+ let started = 0;
645
+ for (const candidate of wanted) {
646
+ if (this.active.has(candidate.id)) continue;
647
+ const pooled = this.idle.get(candidate.type)?.pop();
648
+ if (pooled !== void 0) {
649
+ this.activate(candidate, pooled);
650
+ continue;
651
+ }
652
+ if (this.loading.has(candidate.type) || started >= 1) continue;
653
+ started++;
654
+ this.load(candidate.type);
655
+ }
656
+ }
657
+ activate(candidate, visual) {
658
+ const data = this.options.models.vehicle(candidate.type);
659
+ if (data === void 0) return;
660
+ const paint = new THREE.Color(candidate.color);
661
+ visual.object.traverse((object) => {
662
+ const mesh = object;
663
+ if (!mesh.isMesh) return;
664
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) if (material.name === data.visual.paintMaterial && "color" in material) material.color.copy(paint);
665
+ });
666
+ visual.object.visible = true;
667
+ this.active.set(candidate.id, {
668
+ type: candidate.type,
669
+ visual,
670
+ wheelAngle: 0,
671
+ yaw: NaN,
672
+ steer: 0,
673
+ wheelRadius: data.spec.wheelRadius,
674
+ wheelbase: data.spec.wheelbase
675
+ });
676
+ }
677
+ async load(type) {
678
+ const data = this.options.models.vehicle(type);
679
+ if (data === void 0) {
680
+ this.missing.add(type);
681
+ return;
682
+ }
683
+ this.loading.add(type);
684
+ try {
685
+ const model = await this.options.models.load(type);
686
+ if (model === void 0) {
687
+ this.missing.add(type);
688
+ return;
689
+ }
690
+ if (this.disposed) return;
691
+ const visual = createVehicleVisual(model, data);
692
+ visual.object.visible = false;
693
+ visual.object.traverse((object) => {
694
+ object.userData.walkIgnore = true;
695
+ });
696
+ this.group.add(visual.object);
697
+ await this.options.prepare?.(visual.object);
698
+ if (this.disposed) {
699
+ visual.dispose();
700
+ return;
701
+ }
702
+ const pool = this.idle.get(type) ?? [];
703
+ pool.push(visual);
704
+ this.idle.set(type, pool);
705
+ } catch {
706
+ this.missing.add(type);
707
+ } finally {
708
+ this.loading.delete(type);
709
+ }
710
+ }
711
+ /** Place promoted cars and turn their wheels (every frame). */
712
+ update(id, pos, rot, speed, dt) {
713
+ const entry = this.active.get(id);
714
+ if (entry === void 0) return;
715
+ const object = entry.visual.object;
716
+ object.position.set(pos[0], pos[1], pos[2]);
717
+ object.quaternion.set(rot[0], rot[1], rot[2], rot[3]);
718
+ const yaw = Math.atan2(2 * (rot[3] * rot[1] + rot[0] * rot[2]), 1 - 2 * (rot[1] * rot[1] + rot[0] * rot[0]));
719
+ if (Number.isFinite(entry.yaw) && dt > 0 && speed > .3) {
720
+ let delta = yaw - entry.yaw;
721
+ if (delta > Math.PI) delta -= Math.PI * 2;
722
+ if (delta < -Math.PI) delta += Math.PI * 2;
723
+ const target = Math.max(-.5, Math.min(.5, Math.atan(-(delta / dt) * entry.wheelbase / speed)));
724
+ entry.steer += (target - entry.steer) * Math.min(1, dt * 8);
725
+ } else entry.steer *= .9;
726
+ entry.yaw = yaw;
727
+ entry.wheelAngle = (entry.wheelAngle + speed * dt / Math.max(.2, entry.wheelRadius)) % (Math.PI * 2);
728
+ entry.visual.update(entry.steer, entry.wheelAngle);
729
+ }
730
+ dispose() {
731
+ this.disposed = true;
732
+ for (const entry of this.active.values()) entry.visual.dispose();
733
+ for (const pool of this.idle.values()) for (const visual of pool) visual.dispose();
734
+ this.active.clear();
735
+ this.idle.clear();
736
+ this.group.removeFromParent();
737
+ }
738
+ };
739
+ //#endregion
740
+ //#region src/client/renderer.ts
741
+ const DEFAULT_BUDGET = {
742
+ detailedCars: 8,
743
+ skinnedFigures: 32,
744
+ figureRadius: 120,
745
+ posesPerFrame: 20
746
+ };
747
+ const FADE_TICKS = 30;
748
+ const Figure = componentHandle("figure");
749
+ function createAmbientRenderer(options) {
750
+ const { world } = options;
751
+ const object = new THREE.Group();
752
+ object.name = "ambient";
753
+ options.parent.add(object);
754
+ const prepareSync = (target) => {
755
+ options.prepare?.(target);
756
+ };
757
+ const batches = new ProxyBatches(prepareSync);
758
+ object.add(batches.group);
759
+ const detail = options.vehicles !== void 0 ? new VehicleDetail({
760
+ models: options.vehicles,
761
+ parent: object,
762
+ ...options.prepare !== void 0 ? { prepare: options.prepare } : {}
763
+ }) : void 0;
764
+ const figures = new AmbientFigures(prepareSync);
765
+ object.add(figures.group);
766
+ const aircraft = options.aircraft !== void 0 ? new AmbientAircraft(options.aircraft, object, options.prepare) : void 0;
767
+ let budget = {
768
+ ...DEFAULT_BUDGET,
769
+ ...options.budget
770
+ };
771
+ const applyBudget = () => {
772
+ detail?.setMax(budget.detailedCars);
773
+ figures.setBudget({
774
+ skinned: budget.skinnedFigures,
775
+ radius: budget.figureRadius,
776
+ posesPerFrame: budget.posesPerFrame
777
+ });
778
+ };
779
+ applyBudget();
780
+ const colors = /* @__PURE__ */ new Map();
781
+ const colorOf = (hex) => {
782
+ const key = hex ?? "#d8d8d4";
783
+ let color = colors.get(key);
784
+ if (color === void 0) {
785
+ color = new THREE.Color(key);
786
+ colors.set(key, color);
787
+ }
788
+ return color;
789
+ };
790
+ let lastSelect = Number.NEGATIVE_INFINITY;
791
+ let elapsed = 0;
792
+ let counts = {
793
+ cars: 0,
794
+ pedestrians: 0,
795
+ trains: 0,
796
+ aircraft: 0,
797
+ proxies: 0,
798
+ detailedCars: 0,
799
+ figures: 0,
800
+ drawBatches: 0
801
+ };
802
+ return {
803
+ object,
804
+ update(camera, dt) {
805
+ elapsed += dt;
806
+ if (!object.visible) return;
807
+ const tick = world.tick;
808
+ batches.begin(camera);
809
+ const walkers = [];
810
+ const planes = [];
811
+ const candidates = [];
812
+ const next = {
813
+ cars: 0,
814
+ pedestrians: 0,
815
+ trains: 0,
816
+ aircraft: 0
817
+ };
818
+ for (const [id, a, t] of world.query(AmbientAgent, Transform)) {
819
+ const agent = a;
820
+ if (agent.kind === "pedestrian") {
821
+ next.pedestrians++;
822
+ const figure = world.get(id, Figure);
823
+ if (figure !== void 0) walkers.push({
824
+ id,
825
+ figure,
826
+ pos: t.pos,
827
+ rot: t.rot,
828
+ speed: agent.speed,
829
+ since: agent.since,
830
+ hidden: agent.hidden === true
831
+ });
832
+ continue;
833
+ }
834
+ if (agent.kind === "car") next.cars++;
835
+ else if (agent.kind === "train") next.trains++;
836
+ else next.aircraft++;
837
+ if (agent.hidden === true) continue;
838
+ if (agent.kind === "aircraft") {
839
+ planes.push({
840
+ id,
841
+ type: agent.type,
842
+ pos: t.pos,
843
+ rot: t.rot,
844
+ speed: agent.speed,
845
+ descending: agent.air !== void 0 && agent.air.y1 < agent.air.y0
846
+ });
847
+ if (aircraft?.modelled(id) === true) continue;
848
+ }
849
+ if (agent.kind === "car" || agent.kind === "train") {
850
+ const distance = Math.max(0, Math.hypot(t.pos[0] - camera[0], t.pos[1] - camera[1], t.pos[2] - camera[2]) - agent.length / 2);
851
+ if (distance < 80) candidates.push({
852
+ id,
853
+ type: agent.type,
854
+ color: agent.color ?? "#d8d8d4",
855
+ distance
856
+ });
857
+ if (detail?.has(id) === true) {
858
+ detail.update(id, t.pos, t.rot, agent.speed, dt);
859
+ continue;
860
+ }
861
+ }
862
+ const shape = proxyShapeFor(agent.kind, agent.length);
863
+ const height = options.heights?.[agent.type] ?? proxyHeight(shape, agent.length, agent.width, agent.type);
864
+ const age = tick - agent.spawnedTick;
865
+ batches.add({
866
+ shape,
867
+ dims: {
868
+ length: agent.length,
869
+ width: agent.width,
870
+ height
871
+ },
872
+ pos: t.pos,
873
+ rot: t.rot,
874
+ scale: age >= FADE_TICKS ? 1 : Math.max(.05, age / FADE_TICKS),
875
+ color: colorOf(agent.color)
876
+ });
877
+ }
878
+ const proxies = batches.end();
879
+ figures.update(walkers, camera, tick, world.tickRate);
880
+ aircraft?.sync(planes, dt);
881
+ if (detail !== void 0 && elapsed - lastSelect >= .2) {
882
+ lastSelect = elapsed;
883
+ detail.select(candidates, (id) => world.exists(id));
884
+ }
885
+ counts = {
886
+ ...next,
887
+ proxies,
888
+ detailedCars: detail?.count ?? 0,
889
+ figures: figures.count,
890
+ drawBatches: batches.meshCount
891
+ };
892
+ },
893
+ setBudget(next) {
894
+ budget = {
895
+ ...budget,
896
+ ...next
897
+ };
898
+ applyBudget();
899
+ },
900
+ setVisible(visible) {
901
+ object.visible = visible;
902
+ },
903
+ stats: () => counts,
904
+ dispose() {
905
+ detail?.dispose();
906
+ aircraft?.dispose();
907
+ figures.dispose();
908
+ batches.dispose();
909
+ object.removeFromParent();
910
+ }
911
+ };
912
+ }
913
+ //#endregion
914
+ //#region src/client.ts
915
+ /**
916
+ * @bendyline/molen-ambient/client — rendering for ambient NPCs: instanced vehicle proxies with
917
+ * pooled full models near the camera, procedural pedestrians and aircraft for main-thread worlds
918
+ * (`createAmbientRenderer`), and the `ambient-vehicle` renderable kind for Worker hosts.
919
+ */
920
+ registerAmbientSchema();
921
+ //#endregion
922
+ export { AmbientFigures, ProxyBatches, ambientVehicleKind, createAmbientRenderer, proxyGeometry, proxyHeight, proxyShapeFor };