@bendyline/molen-ambient 0.0.8 → 0.0.10

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/client.d.mts CHANGED
@@ -12,7 +12,7 @@ interface AmbientAircraftModels {
12
12
  }
13
13
  //#endregion
14
14
  //#region src/client/proxies.d.ts
15
- type ProxyShape = "car" | "bus" | "rail" | "aircraft";
15
+ type ProxyShape = "car" | "bus" | "rail" | "aircraft" | "boat";
16
16
  interface ProxyDimensions {
17
17
  length: number;
18
18
  width: number;
@@ -75,11 +75,29 @@ interface DetailCandidate {
75
75
  interface WalkerView {
76
76
  id: string;
77
77
  figure: FigureData;
78
+ /** World position of the walker's `anchor` point (its feet unless `anchor` says otherwise). */
78
79
  pos: readonly [number, number, number];
79
80
  rot: readonly [number, number, number, number];
81
+ /** Planar speed, m/s. */
80
82
  speed: number;
83
+ /** Tick the current motion began. */
81
84
  since: number;
82
85
  hidden: boolean;
86
+ /**
87
+ * The gait: `idle` or `walk` from `speed` by default, `run` for the running gait, `sit` for a
88
+ * seated pose (a passenger). Seated and eye-anchored walkers draw only at the animated detail
89
+ * tiers, since a rigid stand-in cannot sit.
90
+ */
91
+ mode?: "idle" | "walk" | "run" | "sit";
92
+ /**
93
+ * Which point of the body sits at `pos`: the feet (`origin`, default) or the eye (`eye`, the
94
+ * point a vehicle seat names).
95
+ */
96
+ anchor?: "origin" | "eye" | "pelvis";
97
+ /** Saddle-relative cycle contact points, shared with the kernel pose evaluator. */
98
+ riding?: import("@bendyline/molen-figures/client").PoseEvalOptions["riding"];
99
+ /** A world point the head turns toward (within the neck's reach). */
100
+ lookAt?: readonly [number, number, number];
83
101
  }
84
102
  interface FigureBudget {
85
103
  /** Skinned (animated) figures at most. */
@@ -125,6 +143,8 @@ declare function ambientVehicleKind(options?: AmbientVehicleKindOptions): Render
125
143
  interface AmbientRenderBudget {
126
144
  /** Cars drawn with their full model at most. */
127
145
  detailedCars: number;
146
+ /** Full vessel models at most (default 4). */
147
+ detailedBoats?: number;
128
148
  /** Animated (skinned) pedestrians at most. */
129
149
  skinnedFigures: number;
130
150
  /** Pedestrians beyond this distance (m) are not drawn. */
@@ -151,8 +171,10 @@ interface AmbientRenderStats {
151
171
  pedestrians: number;
152
172
  trains: number;
153
173
  aircraft: number;
174
+ boats: number;
154
175
  proxies: number;
155
176
  detailedCars: number;
177
+ detailedBoats: number;
156
178
  figures: number;
157
179
  drawBatches: number;
158
180
  }
package/dist/client.mjs CHANGED
@@ -1,9 +1,9 @@
1
- import { d as registerAmbientSchema, r as AmbientAgent } from "./components-CupqU6fR.mjs";
1
+ import { d as registerAmbientSchema, r as AmbientAgent } from "./components-D4HrizHN.mjs";
2
2
  import { Transform, componentHandle } from "@bendyline/molen-kernel/world";
3
3
  import { createVehicleVisual, vehicleProxyGeometry, vehicleProxyMaterial } from "@bendyline/molen-client/vehicles";
4
4
  import * as THREE from "three";
5
5
  import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
6
- import { FigureGeometryCache, applyPose, evaluatePose, figureBodyToSkinnedMesh, figureSeed, resolveFigureDescriptor, strideRateFor } from "@bendyline/molen-figures/client";
6
+ import { FigureGeometryCache, applyPose, evaluatePose, figureBodyToSkinnedMesh, figureSeed, resolveFigureDescriptor, strideRateFor, worldToFigure } from "@bendyline/molen-figures/client";
7
7
  import { createAircraftVisual } from "@bendyline/molen-client/aircraft";
8
8
  //#region src/client/proxies.ts
9
9
  /**
@@ -69,6 +69,7 @@ function aircraftGeometry({ length, width }) {
69
69
  }
70
70
  /** The shape to draw for an agent kind and its dimensions. */
71
71
  function proxyShapeFor(kind, length) {
72
+ if (kind === "boat") return "boat";
72
73
  if (kind === "train") return "rail";
73
74
  if (kind === "aircraft") return "aircraft";
74
75
  return length > 7.5 ? "bus" : "car";
@@ -77,6 +78,7 @@ function proxyShapeFor(kind, length) {
77
78
  function proxyHeight(shape, length, width, type) {
78
79
  if (shape === "bus") return 3.1;
79
80
  if (shape === "rail") return 3.6;
81
+ if (shape === "boat") return Math.max(2, length * .18);
80
82
  if (shape === "aircraft") return length * .25;
81
83
  if (/van/.test(type) || width >= 1.98) return 2;
82
84
  if (/suv|pickup/.test(type)) return 1.75;
@@ -100,7 +102,17 @@ function proxyGeometry(shape, dims) {
100
102
  });
101
103
  else if (shape === "bus") geometry = busGeometry(d);
102
104
  else if (shape === "rail") geometry = railGeometry(d);
103
- else geometry = aircraftGeometry(d);
105
+ else if (shape === "boat") {
106
+ const hull = box(0, d.height * .08, 0, d.width, d.height * .25, d.length, WHITE);
107
+ const position = hull.getAttribute("position");
108
+ for (let i = 0; i < position.count; i++) if (position.getZ(i) > 0) position.setX(i, position.getX(i) * .15);
109
+ hull.computeVertexNormals();
110
+ geometry = merged([
111
+ hull,
112
+ box(0, d.height * .42, -d.length * .2, d.width * .65, d.height * .45, d.length * .4, WHITE),
113
+ box(0, d.height * .5, -d.length * .2, d.width * .66, d.height * .15, d.length * .36, GLASS)
114
+ ]);
115
+ } else geometry = aircraftGeometry(d);
104
116
  cache.set(key, geometry);
105
117
  return geometry;
106
118
  }
@@ -224,8 +236,14 @@ var ProxyBatches = class {
224
236
  * Pedestrians as procedural figures, posed without the kernel figures systems (so a main-thread
225
237
  * host never loads the script host): gait comes from each agent's speed and the distance it has
226
238
  * 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.
239
+ * tiers follow distance with hysteresis, and pose evaluation is budgeted per frame. A walker can
240
+ * also be seated (`mode: 'sit'`, `anchor: 'eye'` for a vehicle seat) or turn its head toward a
241
+ * point (`lookAt`), which is how a host draws its own characters with the same bodies.
228
242
  */
243
+ /** Whether a walker's pose depends on more than its gait, so a rigid stand-in would be wrong. */
244
+ function posed(walker) {
245
+ return walker.mode === "sit" || walker.anchor !== void 0 && walker.anchor !== "origin";
246
+ }
229
247
  var AmbientFigures = class {
230
248
  prepare;
231
249
  group = new THREE.Group();
@@ -319,6 +337,7 @@ var AmbientFigures = class {
319
337
  let tier = this.tierFor(distance, entry?.tier);
320
338
  if (tier !== void 0 && tier < 2) if (skinned >= this.budget.skinned) tier = 2;
321
339
  else skinned++;
340
+ if (tier === 2 && posed(w)) tier = void 0;
322
341
  if (tier === void 0) {
323
342
  if (entry !== void 0) {
324
343
  this.releaseMesh(entry.key, entry.mesh);
@@ -376,23 +395,40 @@ var AmbientFigures = class {
376
395
  const rest = animated.slice(nearest);
377
396
  for (let i = 0; i < budget - nearest && rest.length > 0 && i < rest.length; i++) chosen.push(rest[(this.cursor + i) % rest.length]);
378
397
  if (rest.length > 0) this.cursor = (this.cursor + budget - nearest) % rest.length;
398
+ const picked = new Set(chosen.map(([id]) => id));
399
+ for (const pair of rest) {
400
+ const walker = byId.get(pair[0]);
401
+ if (pair[1].pose === void 0 && !picked.has(pair[0]) && walker !== void 0 && posed(walker)) chosen.push(pair);
402
+ }
379
403
  for (const [id, entry] of chosen) {
380
404
  const walker = byId.get(id);
381
405
  if (walker === void 0) continue;
382
- const moving = walker.speed > .05;
406
+ const seated = walker.mode === "sit";
407
+ const moving = !seated && walker.speed > .05 && walker.mode !== "idle";
383
408
  const strideRate = moving ? strideRateFor(walker.speed, entry.rig.legLength) : 0;
384
409
  const stride = strideRate > 0 ? walker.speed / strideRate : 1;
385
410
  const state = {
386
- mode: moving ? "walk" : "idle",
387
- speed: walker.speed,
411
+ mode: seated ? "sit" : moving ? walker.mode === "run" ? "run" : "walk" : "idle",
412
+ speed: moving ? walker.speed : 0,
388
413
  strideRate,
389
414
  phaseAt: moving ? entry.walked / stride % 1 : 0,
390
415
  phaseAtTick: tick,
391
416
  modeAtTick: walker.since
392
417
  };
418
+ const lookTarget = walker.lookAt !== void 0 ? worldToFigure({
419
+ pos: [...walker.pos],
420
+ rot: [...walker.rot]
421
+ }, [
422
+ walker.lookAt[0],
423
+ walker.lookAt[1],
424
+ walker.lookAt[2]
425
+ ]) : void 0;
393
426
  entry.pose = evaluatePose(entry.rig, state, tick, {
394
427
  tickRate,
395
- seed: entry.seed
428
+ seed: entry.seed,
429
+ riding: walker.riding,
430
+ ...lookTarget !== void 0 ? { lookTarget } : {},
431
+ ...walker.anchor !== void 0 && walker.anchor !== "origin" ? { anchor: walker.anchor } : {}
396
432
  }, entry.pose);
397
433
  applyPose(entry.pose, entry.mesh.bones);
398
434
  }
@@ -489,6 +525,80 @@ function ambientVehicleKind(options = {}) {
489
525
  * Aircraft overhead: content models (propellers or fans turning) when the host supplies them,
490
526
  * otherwise instanced proxies drawn by the vehicle batches.
491
527
  */
528
+ /** Node names the aircraft visual moves or toggles; everything else on an ambient copy is still. */
529
+ function movingNodes(spec) {
530
+ const visual = spec.visual;
531
+ return new Set([
532
+ ...visual.rotors.map((binding) => binding.node),
533
+ ...visual.gearNodes,
534
+ ...visual.flaps.map((binding) => binding.node),
535
+ ...visual.ailerons.map((binding) => binding.node),
536
+ ...visual.controlStick !== void 0 ? [visual.controlStick.node] : [],
537
+ ...visual.collective !== void 0 ? [visual.collective.node] : [],
538
+ ...visual.animation?.bindings.map((binding) => binding.node) ?? []
539
+ ]);
540
+ }
541
+ /**
542
+ * An aircraft overhead is seen from hundreds of meters, so its hundreds of still parts (fuselage,
543
+ * wings, canopy frame, cockpit) merge into one mesh per material: a copy costs a draw per
544
+ * material plus its moving parts, instead of one per part (281 for the P-51). Moving parts keep
545
+ * their nodes and bindings. The visual is built without the interior, which is never animated
546
+ * overhead. Exported for tests.
547
+ */
548
+ function mergeStaticAircraftParts(model, spec) {
549
+ const moving = movingNodes(spec);
550
+ model.updateMatrixWorld(true);
551
+ const toModel = new THREE.Matrix4().copy(model.matrixWorld).invert();
552
+ const groups = /* @__PURE__ */ new Map();
553
+ const merged = [];
554
+ const visit = (object) => {
555
+ if (moving.has(object.name)) return;
556
+ for (const child of [...object.children]) visit(child);
557
+ const mesh = object;
558
+ if (!mesh.isMesh || Array.isArray(mesh.material) || mesh.isSkinnedMesh) return;
559
+ const source = mesh.geometry;
560
+ if (source.morphAttributes.position !== void 0) return;
561
+ const geometry = new THREE.BufferGeometry();
562
+ for (const name of [
563
+ "position",
564
+ "normal",
565
+ "color"
566
+ ]) {
567
+ const attribute = source.getAttribute(name);
568
+ if (attribute === void 0) continue;
569
+ const copy = new Float32Array(attribute.count * attribute.itemSize);
570
+ for (let i = 0; i < attribute.count; i++) for (let c = 0; c < attribute.itemSize; c++) copy[i * attribute.itemSize + c] = attribute.getComponent(i, c);
571
+ geometry.setAttribute(name, new THREE.BufferAttribute(copy, attribute.itemSize));
572
+ }
573
+ if (source.index !== null) geometry.setIndex(source.index.clone());
574
+ geometry.applyMatrix4(new THREE.Matrix4().multiplyMatrices(toModel, mesh.matrixWorld));
575
+ const key = `${mesh.material.uuid}|${[...Object.keys(geometry.attributes)].sort().join()}|${geometry.index !== null}`;
576
+ const group = groups.get(key) ?? {
577
+ material: mesh.material,
578
+ parts: []
579
+ };
580
+ group.parts.push(geometry);
581
+ groups.set(key, group);
582
+ mesh.removeFromParent();
583
+ };
584
+ visit(model);
585
+ for (const { material, parts } of groups.values()) {
586
+ const geometry = mergeGeometries(parts, false);
587
+ for (const part of parts) part.dispose();
588
+ if (geometry === null) continue;
589
+ const mesh = new THREE.Mesh(geometry, material);
590
+ mesh.name = `ambient-merged:${material.name}`;
591
+ merged.push(mesh);
592
+ }
593
+ for (const mesh of merged) model.add(mesh);
594
+ }
595
+ /** Move toward a selection at `time` seconds for full travel; 0, unset or a first sight is instant. */
596
+ function travel(position, selected, time, dt) {
597
+ const target = selected ? 1 : 0;
598
+ if (time === void 0 || time <= 0 || Number.isNaN(position)) return target;
599
+ const step = dt / time;
600
+ return position + Math.max(-step, Math.min(step, target - position));
601
+ }
492
602
  const INPUT = {
493
603
  power: .8,
494
604
  pitch: 0,
@@ -527,6 +637,9 @@ var AmbientAircraft = class {
527
637
  continue;
528
638
  }
529
639
  entry.rotor = (entry.rotor + dt * 40) % (Math.PI * 2);
640
+ const airplane = entry.spec.airplane;
641
+ entry.gear = travel(entry.gear, plane.descending, airplane?.gearTransitTime, dt);
642
+ entry.flaps = travel(entry.flaps, plane.descending, airplane?.flapTransitTime, dt);
530
643
  const object = entry.visual.object;
531
644
  object.position.set(plane.pos[0] ?? 0, plane.pos[1] ?? 0, plane.pos[2] ?? 0);
532
645
  object.quaternion.set(plane.rot[0] ?? 0, plane.rot[1] ?? 0, plane.rot[2] ?? 0, plane.rot[3] ?? 1);
@@ -538,7 +651,9 @@ var AmbientAircraft = class {
538
651
  pitch: 0,
539
652
  roll: 0,
540
653
  rpm: 2400,
541
- verticalSpeed: 0
654
+ verticalSpeed: 0,
655
+ gearPosition: entry.gear,
656
+ flapPosition: entry.flaps
542
657
  }, {
543
658
  ...INPUT,
544
659
  gear: plane.descending,
@@ -565,7 +680,14 @@ var AmbientAircraft = class {
565
680
  return;
566
681
  }
567
682
  if (this.disposed) return;
568
- const visual = createAircraftVisual(model, spec);
683
+ mergeStaticAircraftParts(model, spec);
684
+ const visual = createAircraftVisual(model, {
685
+ ...spec,
686
+ visual: {
687
+ ...spec.visual,
688
+ interior: void 0
689
+ }
690
+ });
569
691
  visual.object.traverse((object) => {
570
692
  object.userData.walkIgnore = true;
571
693
  object.castShadow = false;
@@ -578,7 +700,10 @@ var AmbientAircraft = class {
578
700
  }
579
701
  this.active.set(id, {
580
702
  visual,
581
- rotor: 0
703
+ rotor: 0,
704
+ gear: NaN,
705
+ flaps: NaN,
706
+ spec
582
707
  });
583
708
  } catch {
584
709
  this.missing.add(type);
@@ -740,6 +865,7 @@ var VehicleDetail = class {
740
865
  //#region src/client/renderer.ts
741
866
  const DEFAULT_BUDGET = {
742
867
  detailedCars: 8,
868
+ detailedBoats: 4,
743
869
  skinnedFigures: 32,
744
870
  figureRadius: 120,
745
871
  posesPerFrame: 20
@@ -761,6 +887,13 @@ function createAmbientRenderer(options) {
761
887
  parent: object,
762
888
  ...options.prepare !== void 0 ? { prepare: options.prepare } : {}
763
889
  }) : void 0;
890
+ const boatDetail = options.vehicles !== void 0 ? new VehicleDetail({
891
+ models: options.vehicles,
892
+ parent: object,
893
+ near: 1200,
894
+ far: 1500,
895
+ ...options.prepare !== void 0 ? { prepare: options.prepare } : {}
896
+ }) : void 0;
764
897
  const figures = new AmbientFigures(prepareSync);
765
898
  object.add(figures.group);
766
899
  const aircraft = options.aircraft !== void 0 ? new AmbientAircraft(options.aircraft, object, options.prepare) : void 0;
@@ -770,6 +903,7 @@ function createAmbientRenderer(options) {
770
903
  };
771
904
  const applyBudget = () => {
772
905
  detail?.setMax(budget.detailedCars);
906
+ boatDetail?.setMax(budget.detailedBoats ?? 4);
773
907
  figures.setBudget({
774
908
  skinned: budget.skinnedFigures,
775
909
  radius: budget.figureRadius,
@@ -794,8 +928,10 @@ function createAmbientRenderer(options) {
794
928
  pedestrians: 0,
795
929
  trains: 0,
796
930
  aircraft: 0,
931
+ boats: 0,
797
932
  proxies: 0,
798
933
  detailedCars: 0,
934
+ detailedBoats: 0,
799
935
  figures: 0,
800
936
  drawBatches: 0
801
937
  };
@@ -809,11 +945,13 @@ function createAmbientRenderer(options) {
809
945
  const walkers = [];
810
946
  const planes = [];
811
947
  const candidates = [];
948
+ const boatCandidates = [];
812
949
  const next = {
813
950
  cars: 0,
814
951
  pedestrians: 0,
815
952
  trains: 0,
816
- aircraft: 0
953
+ aircraft: 0,
954
+ boats: 0
817
955
  };
818
956
  for (const [id, a, t] of world.query(AmbientAgent, Transform)) {
819
957
  const agent = a;
@@ -833,6 +971,7 @@ function createAmbientRenderer(options) {
833
971
  }
834
972
  if (agent.kind === "car") next.cars++;
835
973
  else if (agent.kind === "train") next.trains++;
974
+ else if (agent.kind === "boat") next.boats++;
836
975
  else next.aircraft++;
837
976
  if (agent.hidden === true) continue;
838
977
  if (agent.kind === "aircraft") {
@@ -846,6 +985,19 @@ function createAmbientRenderer(options) {
846
985
  });
847
986
  if (aircraft?.modelled(id) === true) continue;
848
987
  }
988
+ if (agent.kind === "boat") {
989
+ const distance = Math.hypot(t.pos[0] - camera[0], t.pos[1] - camera[1], t.pos[2] - camera[2]);
990
+ boatCandidates.push({
991
+ id,
992
+ type: agent.type,
993
+ color: agent.color ?? "#d8d8d4",
994
+ distance
995
+ });
996
+ if (boatDetail?.has(id) === true) {
997
+ boatDetail.update(id, t.pos, t.rot, agent.speed, dt);
998
+ continue;
999
+ }
1000
+ }
849
1001
  if (agent.kind === "car" || agent.kind === "train") {
850
1002
  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
1003
  if (distance < 80) candidates.push({
@@ -881,11 +1033,13 @@ function createAmbientRenderer(options) {
881
1033
  if (detail !== void 0 && elapsed - lastSelect >= .2) {
882
1034
  lastSelect = elapsed;
883
1035
  detail.select(candidates, (id) => world.exists(id));
1036
+ boatDetail?.select(boatCandidates, (id) => world.exists(id));
884
1037
  }
885
1038
  counts = {
886
1039
  ...next,
887
1040
  proxies,
888
1041
  detailedCars: detail?.count ?? 0,
1042
+ detailedBoats: boatDetail?.count ?? 0,
889
1043
  figures: figures.count,
890
1044
  drawBatches: batches.meshCount
891
1045
  };
@@ -903,6 +1057,7 @@ function createAmbientRenderer(options) {
903
1057
  stats: () => counts,
904
1058
  dispose() {
905
1059
  detail?.dispose();
1060
+ boatDetail?.dispose();
906
1061
  aircraft?.dispose();
907
1062
  figures.dispose();
908
1063
  batches.dispose();
@@ -23,14 +23,19 @@ const KIND_SPEED = {
23
23
  path: 1.4,
24
24
  crossing: 1.4,
25
25
  rail: 20,
26
- tram: 12
26
+ tram: 12,
27
+ ferry: 8,
28
+ channel: 7
27
29
  };
28
30
  /** Classify a mapped feature; `undefined` for features no agent uses. */
29
31
  function classifyFeature(feature) {
30
32
  const cls = feature.class.toLowerCase();
31
33
  const sub = (feature.subclass ?? "").toLowerCase();
32
34
  if (cls === "aeroway" || /runway|taxiway|apron/.test(sub)) return sub === "runway" || cls === "runway" ? "runway" : void 0;
33
- if (cls === "ferry" || sub === "ferry") return void 0;
35
+ if (cls === "ferry" || sub === "ferry") return {
36
+ class: "water",
37
+ kind: "ferry"
38
+ };
34
39
  const kind = transportKind(feature);
35
40
  if (kind === "rail") {
36
41
  if (/disused|abandoned|construction|proposed|platform|station|miniature|funicular/.test(sub)) return void 0;
@@ -195,7 +200,7 @@ function featureDrafts(input, options) {
195
200
  }
196
201
  if (feature.tunnel === true && options.tunnels === "skip") continue;
197
202
  const kind = transportKind(feature);
198
- const width = classified.class === "walk" ? dmath.max(1.2, feature.width ?? 2.4) : classified.class === "rail" ? 3 : transportWidth(feature, kind);
203
+ const width = classified.class === "water" ? feature.width ?? 60 : classified.class === "walk" ? dmath.max(1.2, feature.width ?? 2.4) : classified.class === "rail" ? 3 : transportWidth(feature, kind);
199
204
  const lanes = classified.class === "road" ? roadLanes(feature, width).total : 2;
200
205
  const link = isTransportLink(feature);
201
206
  for (const line of joinTerrainLines(feature.lines)) for (const piece of clipPolyline(toWorld(line), minX, minZ, maxX, maxZ)) {
@@ -205,7 +210,7 @@ function featureDrafts(input, options) {
205
210
  points: piece,
206
211
  width,
207
212
  lanes,
208
- oneway: feature.oneway === true && classified.class === "road",
213
+ oneway: feature.oneway === true && (classified.class === "road" || classified.class === "water"),
209
214
  layer: feature.layer ?? 0,
210
215
  bridge: feature.bridge === true,
211
216
  tunnel: feature.tunnel === true,
@@ -227,6 +232,7 @@ function featureDrafts(input, options) {
227
232
  };
228
233
  }
229
234
  const POI_KINDS = new Set([
235
+ "ferry_terminal",
230
236
  "station",
231
237
  "tram_stop",
232
238
  "bus_stop",
@@ -291,6 +297,14 @@ function wayDraft(way) {
291
297
  ...way.speed !== void 0 ? { speed: way.speed } : {},
292
298
  ...way.name !== void 0 ? { name: way.name } : {}
293
299
  };
300
+ if (way.class === "water") return {
301
+ ...common,
302
+ class: "water",
303
+ kind: way.subclass === "ferry" ? "ferry" : "channel",
304
+ width: way.width ?? 60,
305
+ lanes: way.oneway ? 1 : 2,
306
+ oneway: way.oneway === true
307
+ };
294
308
  if (way.class === "rail") return {
295
309
  ...common,
296
310
  class: "rail",
@@ -326,7 +340,7 @@ function wayDraft(way) {
326
340
  function documentPois(doc) {
327
341
  const pois = [];
328
342
  for (const station of doc.stations ?? []) pois.push({
329
- kind: station.kind === "rail" ? "station" : "bus_stop",
343
+ kind: station.kind === "ferry" ? "ferry_terminal" : station.kind === "rail" ? "station" : "bus_stop",
330
344
  x: station.at[0],
331
345
  z: station.at[1],
332
346
  name: station.id,
@@ -412,7 +426,8 @@ const kind = z.enum([
412
426
  "car",
413
427
  "pedestrian",
414
428
  "train",
415
- "aircraft"
429
+ "aircraft",
430
+ "boat"
416
431
  ]);
417
432
  const ambientAgentSchema = z.strictObject({
418
433
  kind: kind.describe("Agent class."),
@@ -421,6 +436,7 @@ const ambientAgentSchema = z.strictObject({
421
436
  lane: z.string().describe("Lane id the agent is on (\"\" for aircraft)."),
422
437
  s: num.describe("Metres along the lane; negative while on the connector into it."),
423
438
  speed: num.nonnegative().describe("Speed along the lane in m/s."),
439
+ cruise: num.positive().describe("Vessel cruise limit in m/s.").optional(),
424
440
  prev: z.string().describe("Previous lane (its connector leads onto `lane`).").optional(),
425
441
  next: z.string().describe("Chosen next lane.").optional(),
426
442
  seed: z.int().nonnegative().describe("Per-agent seed for every random choice it makes."),
@@ -460,7 +476,9 @@ const ambientRoleSchema = z.strictObject({
460
476
  "car",
461
477
  "bus",
462
478
  "rail",
463
- "aircraft"
479
+ "aircraft",
480
+ "boat",
481
+ "ferry"
464
482
  ]).describe("Which ambient pool the type joins (buses drive with cars)."),
465
483
  length: num.positive().describe("Body length in metres (default from vehicle.spec).").optional(),
466
484
  width: num.positive().describe("Body width in metres (default from vehicle.spec).").optional(),
@@ -500,7 +518,8 @@ const waySchema = z.strictObject({
500
518
  "road",
501
519
  "rail",
502
520
  "path",
503
- "air"
521
+ "air",
522
+ "water"
504
523
  ]).describe("What moves on it."),
505
524
  subclass: z.string().describe("motorway, trunk, primary, secondary, tertiary, residential, service; rail/tram; crossing.").optional(),
506
525
  points: z.array(point).min(2).describe("[x, z] or [x, y, z] points in scene metres (y = road surface height)."),
@@ -529,7 +548,11 @@ const transportNetworkSchema = z.strictObject({
529
548
  stations: z.array(z.strictObject({
530
549
  id: z.string().min(1),
531
550
  at: vec2.describe("[x, z]; projected onto the nearest rail (rail) or footway (bus)."),
532
- kind: z.enum(["rail", "bus"]),
551
+ kind: z.enum([
552
+ "rail",
553
+ "bus",
554
+ "ferry"
555
+ ]),
533
556
  dwell: num.positive().describe("Dwell time in seconds.").optional()
534
557
  })).describe("Stops trains (and buses) serve.").optional(),
535
558
  signals: z.array(z.strictObject({
@@ -595,7 +618,7 @@ function registerAmbientSchema() {
595
618
  const owner = "ambient";
596
619
  const docsRef = "guide/ambient-life.md";
597
620
  registerComponent(AMBIENT_AGENT_COMPONENT, ambientAgentSchema, {
598
- description: "Kernel-owned state of an ambient NPC (car, pedestrian, train car or aircraft): its lane, position along it, speed and routing. Read it; the ambient systems write it.",
621
+ description: "Kernel-owned state of an ambient NPC (car, pedestrian, train car, aircraft or boat): its lane, position along it, speed and routing. Read it; the ambient systems write it.",
599
622
  owner,
600
623
  examples: [AMBIENT_AGENT_EXAMPLE],
601
624
  docsRef
@@ -610,7 +633,7 @@ function registerAmbientSchema() {
610
633
  docsRef
611
634
  }, { override: true });
612
635
  registerComponent(AMBIENT_ROLE_COMPONENT, ambientRoleSchema, {
613
- description: "On an entity type: makes it an ambient NPC candidate (car, bus, rail car or aircraft) with dimensions, speeds and spawn weight.",
636
+ description: "On an entity type: makes it an ambient NPC candidate (car, bus, rail car, aircraft, boat or ferry) with dimensions, speeds and spawn weight.",
614
637
  owner,
615
638
  examples: [{
616
639
  role: "car",
@@ -661,7 +684,8 @@ const AMBIENT_KINDS = [
661
684
  "car",
662
685
  "pedestrian",
663
686
  "train",
664
- "aircraft"
687
+ "aircraft",
688
+ "boat"
665
689
  ];
666
690
  const AmbientAgent = defineComponent(AMBIENT_AGENT_COMPONENT);
667
691
  const AmbientObserver = defineComponent(AMBIENT_OBSERVER_COMPONENT);
package/dist/kernel.d.mts CHANGED
@@ -5,7 +5,7 @@ import { TerrainLinePath, TerrainPoiFeature, TerrainTransportationFeature } from
5
5
 
6
6
  //#region src/kernel/components.d.ts
7
7
  /** An ambient NPC class. */
8
- type AmbientKind = "car" | "pedestrian" | "train" | "aircraft";
8
+ type AmbientKind = "car" | "pedestrian" | "train" | "aircraft" | "boat";
9
9
  declare const AMBIENT_KINDS: readonly AmbientKind[];
10
10
  /** An aircraft corridor: a straight line flown at linearly varying altitude. */
11
11
  interface AmbientAirCorridor extends JsonObject {
@@ -24,6 +24,8 @@ interface AmbientAgentData extends JsonObject {
24
24
  lane: string;
25
25
  s: number;
26
26
  speed: number;
27
+ /** Vessel cruise limit, stored so checkpoint/replay does not depend on a mutable type pool. */
28
+ cruise?: number;
27
29
  prev?: string;
28
30
  next?: string;
29
31
  seed: number;
@@ -55,7 +57,7 @@ interface AmbientRoleVisual extends JsonObject {
55
57
  gearNodes?: string[];
56
58
  }
57
59
  interface AmbientRoleData extends JsonObject {
58
- role: "car" | "bus" | "rail" | "aircraft";
60
+ role: "car" | "bus" | "rail" | "aircraft" | "boat" | "ferry";
59
61
  length?: number;
60
62
  width?: number;
61
63
  height?: number;
@@ -127,8 +129,10 @@ interface AmbientPolicy {
127
129
  pedestrian: AmbientClassPolicy;
128
130
  train: AmbientClassPolicy;
129
131
  aircraft: AmbientClassPolicy;
132
+ boat: AmbientClassPolicy;
130
133
  driver: DriverParams;
131
134
  rail: DriverParams;
135
+ marine: DriverParams;
132
136
  }
133
137
  declare const DEFAULT_POLICY: AmbientPolicy;
134
138
  type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] };
@@ -140,6 +144,7 @@ interface AmbientBudget {
140
144
  pedestrians?: number;
141
145
  trains?: number;
142
146
  aircraft?: number;
147
+ boats?: number;
143
148
  /** Outer spawn radius for cars; trains keep their ratio to it. */
144
149
  radius?: number;
145
150
  /** Outer spawn radius for pedestrians. */
@@ -159,9 +164,9 @@ declare function stoppingDistance(v: number, b: number): number;
159
164
  //#endregion
160
165
  //#region src/kernel/graph/types.d.ts
161
166
  /** Which agents a lane serves. */
162
- type TransportClass = "road" | "rail" | "walk" | "air";
167
+ type TransportClass = "road" | "rail" | "walk" | "air" | "water";
163
168
  /** Finer classification used for speeds, spawn preferences and routing weights. */
164
- type RoadKind = "motorway" | "trunk" | "primary" | "secondary" | "tertiary" | "street" | "living" | "service" | "path" | "crossing" | "rail" | "tram";
169
+ type RoadKind = "motorway" | "trunk" | "primary" | "secondary" | "tertiary" | "street" | "living" | "service" | "path" | "crossing" | "rail" | "tram" | "channel" | "ferry";
165
170
  type TurnKind = "straight" | "left" | "right" | "uturn" | "merge";
166
171
  /** An endpoint or split point shared by edges. */
167
172
  interface TransportNode {
@@ -231,7 +236,7 @@ interface TransportLane {
231
236
  interface LaneStop {
232
237
  /** Edge-path distance of the stop (convert with `laneCoordinate`). */
233
238
  readonly d: number;
234
- readonly kind: "station" | "bus" | "crossing" | "level-crossing";
239
+ readonly kind: "station" | "bus" | "ferry" | "crossing" | "level-crossing";
235
240
  /** Station/crossing id, used to remember a served stop. */
236
241
  readonly id: string;
237
242
  /** Stations: dwell time in seconds (default: a seeded 20–40 s). */
@@ -388,7 +393,7 @@ interface TileDrafts {
388
393
  declare function featureDrafts(input: TileDraftInput, options: FeatureDraftOptions): TileDrafts;
389
394
  /** POIs in world metres, filtered to the kinds agents care about. */
390
395
  interface WorldPoi {
391
- kind: "station" | "tram_stop" | "bus_stop" | "traffic_signals" | "give_way" | "crossing" | "aerodrome";
396
+ kind: "ferry_terminal" | "station" | "tram_stop" | "bus_stop" | "traffic_signals" | "give_way" | "crossing" | "aerodrome";
392
397
  x: number;
393
398
  z: number;
394
399
  name?: string;
@@ -402,7 +407,7 @@ declare const TRANSPORT_NETWORK_FORMAT: "molen/transport-network@1";
402
407
  type TransportNetworkPoint = [number, number] | [number, number, number];
403
408
  interface TransportNetworkWay {
404
409
  id?: string;
405
- class: "road" | "rail" | "path" | "air";
410
+ class: "road" | "rail" | "path" | "air" | "water";
406
411
  subclass?: string;
407
412
  points: TransportNetworkPoint[];
408
413
  oneway?: boolean;
@@ -417,7 +422,7 @@ interface TransportNetworkWay {
417
422
  interface TransportNetworkStation {
418
423
  id: string;
419
424
  at: [number, number];
420
- kind: "rail" | "bus";
425
+ kind: "rail" | "bus" | "ferry";
421
426
  dwell?: number;
422
427
  }
423
428
  interface TransportNetworkSignal {
@@ -539,7 +544,7 @@ interface TransportNetworkStats {
539
544
  }
540
545
  /** A script-added polyline. */
541
546
  interface AmbientPolyline {
542
- class: "road" | "rail" | "path";
547
+ class: "road" | "rail" | "path" | "water";
543
548
  subclass?: string;
544
549
  /** `[x, z]` or `[x, y, z]` points in scene metres. */
545
550
  points: ([number, number] | [number, number, number])[];
@@ -680,6 +685,8 @@ interface AmbientVehicleType {
680
685
  colors?: string[];
681
686
  /** Rail: cars per consist. */
682
687
  cars?: number;
688
+ /** Vessels: ferry service or general navigation channel. */
689
+ waterway?: "ferry" | "channel";
683
690
  }
684
691
  interface AmbientPedestrianType {
685
692
  preset: "human.adult" | "human.elder" | "human.child";
@@ -689,6 +696,7 @@ interface AmbientTypes {
689
696
  car: AmbientVehicleType[];
690
697
  train: AmbientVehicleType[];
691
698
  aircraft: AmbientVehicleType[];
699
+ boat: AmbientVehicleType[];
692
700
  pedestrian: AmbientPedestrianType[];
693
701
  }
694
702
  /** Common real-world car body colours, weighted by repetition. */
package/dist/kernel.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as KIND_SPEED, a as AmbientRole, b as featureDrafts, c as AMBIENT_OBSERVER_COMPONENT, d as registerAmbientSchema, f as TRANSPORT_NETWORK_EXAMPLE, g as wayDraft, h as documentRunways, i as AmbientObserver, l as AMBIENT_ROLE_COMPONENT, m as documentPois, n as AMBIENT_KINDS, o as AmbientState, p as TRANSPORT_NETWORK_FORMAT, r as AmbientAgent, s as AMBIENT_AGENT_COMPONENT, t as AMBIENT_ENTITY, u as AMBIENT_STATE_COMPONENT, v as classifyFeature, x as tilePois, y as clipPolyline } from "./components-CupqU6fR.mjs";
1
+ import { _ as KIND_SPEED, a as AmbientRole, b as featureDrafts, c as AMBIENT_OBSERVER_COMPONENT, d as registerAmbientSchema, f as TRANSPORT_NETWORK_EXAMPLE, g as wayDraft, h as documentRunways, i as AmbientObserver, l as AMBIENT_ROLE_COMPONENT, m as documentPois, n as AMBIENT_KINDS, o as AmbientState, p as TRANSPORT_NETWORK_FORMAT, r as AmbientAgent, s as AMBIENT_AGENT_COMPONENT, t as AMBIENT_ENTITY, u as AMBIENT_STATE_COMPONENT, v as classifyFeature, x as tilePois, y as clipPolyline } from "./components-D4HrizHN.mjs";
2
2
  import { createRng, dmath, lookRotation, quatRotateVec3, seedToInt } from "@bendyline/molen-kernel/determinism";
3
3
  import { Transform, componentHandle } from "@bendyline/molen-kernel/world";
4
4
  import { deepMergeJson, resolvePrefab, validateByKind } from "@bendyline/molen-schema";
@@ -199,7 +199,7 @@ function laneSample() {
199
199
  * the next tick and a keyframe restores exactly.
200
200
  *
201
201
  * Order: gather → occupancy → armed crossings → junction grants → cars → pedestrians → trains
202
- * (leads, then their cars) → aircraft → write changed agents and transforms.
202
+ * (leads, then their cars) → vessels → aircraft → write changed agents and transforms.
203
203
  */
204
204
  const TURN_SPEED = {
205
205
  left: 7,
@@ -231,6 +231,18 @@ function chooseNext(lane, seed, hops) {
231
231
  }
232
232
  return moves[moves.length - 1].to;
233
233
  }
234
+ /** Reject branches narrower/shorter than a vessel before choosing a seeded turn. */
235
+ function chooseVesselNext(net, lane, seed, hops, width, length) {
236
+ const next = lane.next.filter((move) => {
237
+ const target = net.lane(move.to);
238
+ const edge = target !== void 0 ? net.edge(target.edge) : void 0;
239
+ return edge !== void 0 && target !== void 0 && width <= edge.width / (edge.oneway ? 1 : 2) && length + 2 < target.length;
240
+ });
241
+ return chooseNext({
242
+ ...lane,
243
+ next
244
+ }, seed, hops);
245
+ }
234
246
  /** Where an agent is: its lane body, or the connector curve into its lane. */
235
247
  function agentSample(net, agent, out) {
236
248
  if (agent.air !== void 0) {
@@ -321,6 +333,7 @@ function stepAgents(world, env) {
321
333
  for (const ref of refs) {
322
334
  if (ref.lane === void 0 || ref.edge === void 0) continue;
323
335
  if (ref.a.kind === "car") stepRoad(ref, occupancy, granted, armed, env);
336
+ else if (ref.a.kind === "boat") stepVessel(ref, occupancy, env);
324
337
  else if (ref.a.kind === "pedestrian") stepWalker(ref, occupancy, env);
325
338
  else if (ref.a.kind === "train" && ref.a.consist === void 0) stepTrainLead(ref, occupancy, env, consistSize.get(ref.id) ?? 0);
326
339
  }
@@ -394,7 +407,8 @@ function advanceLanes(ref, env) {
394
407
  w.prev = lane.id;
395
408
  w.lane = nextLane.id;
396
409
  w.hops += 1;
397
- const chosen = chooseNext(nextLane, w.seed, w.hops);
410
+ const chosen = w.kind === "boat" ? chooseVesselNext(net, nextLane, w.seed, w.hops, w.width, w.length) : chooseNext(nextLane, w.seed, w.hops);
411
+ if (w.kind === "boat") delete w.served;
398
412
  if (chosen === void 0) delete w.next;
399
413
  else w.next = chosen;
400
414
  lane = nextLane;
@@ -864,6 +878,77 @@ function reverseConsist(ref, env, cars) {
864
878
  ref.edge = net.edge(headLane.edge);
865
879
  delete w.served;
866
880
  }
881
+ /** Kinematic water navigation: slow acceleration, following gaps and scheduled dock dwell. */
882
+ function stepVessel(ref, occupancy, env) {
883
+ const { a, w } = ref;
884
+ const { net, dt, tick, tickRate } = env;
885
+ const lane = ref.lane;
886
+ const edge = ref.edge;
887
+ const p = env.policy.marine;
888
+ if (a.state === "dwell") {
889
+ const stop = lane.stops.find((s) => s.id === a.served);
890
+ if (tick - a.since < (stop?.dwell ?? 30) * tickRate) {
891
+ w.speed = 0;
892
+ return;
893
+ }
894
+ }
895
+ const move = net.movement(a.lane, a.next ?? "");
896
+ let v0 = dmath.min(edge.speed, a.cruise ?? edge.speed);
897
+ if (move?.turn === "uturn" && lane.length - a.s < a.length + 20) v0 = dmath.min(v0, 1.5);
898
+ if (a.s < 0) v0 = dmath.min(v0, 2.5);
899
+ let limit = Number.POSITIVE_INFINITY;
900
+ let gap = Number.POSITIVE_INFINITY;
901
+ let leaderSpeed = 0;
902
+ const leader = leaderOnLane(ref, occupancy);
903
+ if (leader !== void 0) {
904
+ gap = leader.a.s - a.s - (a.length + leader.a.length) / 2;
905
+ limit = leader.a.s - (a.length + leader.a.length) / 2 - p.gap;
906
+ leaderSpeed = leader.a.speed;
907
+ } else if (a.next !== void 0 && move !== void 0) {
908
+ const next = firstOnLane(a.next, occupancy);
909
+ if (next !== void 0) {
910
+ gap = lane.length - a.s + move.length + next.a.s - (a.length + next.a.length) / 2;
911
+ limit = a.s + gap - p.gap;
912
+ leaderSpeed = next.a.speed;
913
+ }
914
+ } else {
915
+ limit = lane.length - a.length / 2;
916
+ gap = limit - a.s + p.gap;
917
+ }
918
+ let dock;
919
+ if (edge.kind === "ferry") {
920
+ for (const stop of lane.stops) {
921
+ if (stop.kind !== "ferry" || stop.id === a.served) continue;
922
+ const at = laneCoordinate(lane, edge, stop.d);
923
+ if (at >= a.s - .1 && (dock === void 0 || at < dock.at)) dock = {
924
+ at,
925
+ id: stop.id
926
+ };
927
+ }
928
+ if (dock === void 0 && move?.turn === "uturn" && a.served !== `end:${lane.id}`) dock = {
929
+ at: lane.length,
930
+ id: `end:${lane.id}`
931
+ };
932
+ }
933
+ if (dock !== void 0 && dock.at - a.s + p.gap < gap) {
934
+ gap = dock.at - a.s + p.gap;
935
+ leaderSpeed = 0;
936
+ limit = dmath.min(limit, dock.at);
937
+ }
938
+ const accel = idmAcceleration(a.speed, v0, gap, a.speed - leaderSpeed, p);
939
+ w.speed = dmath.max(0, a.speed + accel * dt);
940
+ w.s = dmath.min(a.s + w.speed * dt, dmath.max(a.s, limit));
941
+ if (w.s >= limit) w.speed = dmath.min(w.speed, leaderSpeed);
942
+ if (dock !== void 0 && dmath.abs(w.s - dock.at) < .5 && w.speed < .3) {
943
+ w.s = dock.at;
944
+ w.speed = 0;
945
+ w.served = dock.id;
946
+ setState(w, "dwell", tick);
947
+ return;
948
+ }
949
+ advanceLanes(ref, env);
950
+ setState(w, w.speed < .05 ? "wait" : "move", tick);
951
+ }
867
952
  function stepAircraft(ref, env) {
868
953
  const { w } = ref;
869
954
  w.s = ref.a.s + ref.a.speed * env.dt;
@@ -1043,6 +1128,7 @@ function rebuildNodeGroup(store, nodeIds) {
1043
1128
  const cache = new EndCache(store);
1044
1129
  buildRoadMovements(store, cache, roadArms, junction);
1045
1130
  buildRailMovements(store, cache, armsOf(store, group, "rail"));
1131
+ buildWaterMovements(store, cache, armsOf(store, group, "water"));
1046
1132
  buildWalkMovements(store, cache, armsOf(store, group, "walk"), roadArms, junction, maxWidth);
1047
1133
  }
1048
1134
  function buildJunction(store, id, group, arms, radius) {
@@ -1259,6 +1345,27 @@ function buildRoadMovements(store, cache, arms, junction) {
1259
1345
  }
1260
1346
  });
1261
1347
  }
1348
+ /** Keep ferry services separate from navigation channels even where their lines intersect. */
1349
+ function buildWaterMovements(store, cache, arms) {
1350
+ for (const inArm of arms) for (const lane of lanesAt(store, inArm, "water", true)) {
1351
+ const moves = [];
1352
+ for (const outArm of arms) {
1353
+ if (outArm === inArm || outArm.edge.kind !== inArm.edge.kind) continue;
1354
+ for (const target of lanesAt(store, outArm, "water", false)) {
1355
+ const move = movement(cache, lane, target, "straight", 1, void 0, 0);
1356
+ if (move !== void 0) moves.push(move);
1357
+ }
1358
+ }
1359
+ if (moves.length === 0) {
1360
+ const back = lanesAt(store, inArm, "water", false)[0];
1361
+ if (back !== void 0) {
1362
+ const move = movement(cache, lane, back, "uturn", 1, void 0, 0);
1363
+ if (move !== void 0) moves.push(move);
1364
+ }
1365
+ }
1366
+ lane.next = moves;
1367
+ }
1368
+ }
1262
1369
  function buildRailMovements(store, cache, arms) {
1263
1370
  for (const inArm of arms) for (const lane of lanesAt(store, inArm, "rail", true)) {
1264
1371
  const moves = [];
@@ -1343,7 +1450,8 @@ const CLASS_INDEX = {
1343
1450
  road: 0,
1344
1451
  rail: 1,
1345
1452
  walk: 2,
1346
- air: 3
1453
+ air: 3,
1454
+ water: 4
1347
1455
  };
1348
1456
  /** Cumulative distances of a polyline. */
1349
1457
  function cumulative(points) {
@@ -1432,12 +1540,7 @@ function planarSplit(drafts, options = {}) {
1432
1540
  }
1433
1541
  }
1434
1542
  const nodes = [];
1435
- const nodeCells = [
1436
- /* @__PURE__ */ new Map(),
1437
- /* @__PURE__ */ new Map(),
1438
- /* @__PURE__ */ new Map(),
1439
- /* @__PURE__ */ new Map()
1440
- ];
1543
+ const nodeCells = Object.keys(CLASS_INDEX).map(() => /* @__PURE__ */ new Map());
1441
1544
  const nodeAt = (x, z, draft) => {
1442
1545
  const cx = dmath.floor(x / snap);
1443
1546
  const cz = dmath.floor(z / snap);
@@ -1614,7 +1717,8 @@ const CLASSES = [
1614
1717
  "road",
1615
1718
  "rail",
1616
1719
  "walk",
1617
- "air"
1720
+ "air",
1721
+ "water"
1618
1722
  ];
1619
1723
  var LaneGrid = class {
1620
1724
  cells = /* @__PURE__ */ new Map();
@@ -1648,7 +1752,8 @@ var LaneGrid = class {
1648
1752
  road: 0,
1649
1753
  rail: 0,
1650
1754
  walk: 0,
1651
- air: 0
1755
+ air: 0,
1756
+ water: 0
1652
1757
  }
1653
1758
  };
1654
1759
  this.cells.set(key, cell);
@@ -1664,7 +1769,8 @@ var LaneGrid = class {
1664
1769
  road: 0,
1665
1770
  rail: 0,
1666
1771
  walk: 0,
1667
- air: 0
1772
+ air: 0,
1773
+ water: 0
1668
1774
  };
1669
1775
  for (const cls of CLASSES) {
1670
1776
  const m = (d1 - d0) * laneCounts[cls];
@@ -1789,7 +1895,8 @@ var TransportNetwork = class {
1789
1895
  "road",
1790
1896
  "rail",
1791
1897
  "walk",
1792
- "air"
1898
+ "air",
1899
+ "water"
1793
1900
  ]);
1794
1901
  }
1795
1902
  /** Change which lane classes are built (applies to tiles registered afterwards). */
@@ -2013,6 +2120,7 @@ var TransportNetwork = class {
2013
2120
  if (dense.heights !== void 0) dense.heights.forEach((h, i) => {
2014
2121
  ys[i] = h;
2015
2122
  });
2123
+ else if (draft.class === "water") ys.fill(0);
2016
2124
  else if (draft.bridge || draft.bridgeConnections?.length) {
2017
2125
  const deck = bridgeDeckHeightFn(path, heightAt, {
2018
2126
  ...draft.deckElevation !== void 0 ? { deckElevation: draft.deckElevation } : {},
@@ -2062,7 +2170,8 @@ var TransportNetwork = class {
2062
2170
  road: 0,
2063
2171
  rail: 0,
2064
2172
  walk: 0,
2065
- air: 0
2173
+ air: 0,
2174
+ water: 0
2066
2175
  };
2067
2176
  for (const laneId of edge.lanes) counts[this.lanes.get(laneId).class]++;
2068
2177
  this.grid.insert(edge, counts);
@@ -2124,6 +2233,9 @@ var TransportNetwork = class {
2124
2233
  make("sl+", "walk", 1, 1, -o + side * .35, SIDEWALK_LIFT);
2125
2234
  make("sl-", "walk", -1, 1, o + side * .35, SIDEWALK_LIFT);
2126
2235
  }
2236
+ } else if (draft.class === "water") {
2237
+ make("f0", "water", 1, 0, draft.oneway ? 0 : draft.width / 4);
2238
+ if (!draft.oneway) make("b0", "water", -1, 0, draft.width / 4);
2127
2239
  } else if (draft.class === "rail") {
2128
2240
  make("f0", "rail", 1, 0, 0);
2129
2241
  make("b0", "rail", -1, 0, 0);
@@ -2186,13 +2298,16 @@ var TransportNetwork = class {
2186
2298
  record.pois.forEach((poi, i) => {
2187
2299
  const wantRail = poi.kind === "station" || poi.kind === "tram_stop";
2188
2300
  const wantWalk = poi.kind === "bus_stop";
2189
- if (!wantRail && !wantWalk) return;
2190
- const reach = wantRail ? 25 : 12;
2301
+ const wantWater = poi.kind === "ferry_terminal";
2302
+ if (!wantRail && !wantWalk && !wantWater) return;
2303
+ const wanted = wantWater ? "water" : wantRail ? "rail" : "walk";
2304
+ const reach = wantWater ? 80 : wantRail ? 25 : 12;
2191
2305
  let best;
2192
2306
  for (const edgeId of this.grid.edgesNear(poi.x, poi.z, reach)) {
2193
2307
  if (!own.has(edgeId)) continue;
2194
2308
  const edge = this.edges.get(edgeId);
2195
- if (!edge.lanes.some((l) => this.lanes.get(l)?.class === (wantRail ? "rail" : "walk"))) continue;
2309
+ if (wantWater && edge.kind !== "ferry") continue;
2310
+ if (!edge.lanes.some((l) => this.lanes.get(l)?.class === wanted)) continue;
2196
2311
  const hit = projectOnPath(edge.path, poi.x, poi.z);
2197
2312
  if (hit.distance <= reach && (best === void 0 || hit.distance < best.distance)) best = {
2198
2313
  edge,
@@ -2203,13 +2318,13 @@ var TransportNetwork = class {
2203
2318
  if (best === void 0) return;
2204
2319
  const stop = {
2205
2320
  d: best.d,
2206
- kind: wantRail ? "station" : "bus",
2321
+ kind: wantWater ? "ferry" : wantRail ? "station" : "bus",
2207
2322
  id: `${record.key}:${poi.kind}:${i}`,
2208
2323
  ...poi.dwell !== void 0 ? { dwell: poi.dwell } : {}
2209
2324
  };
2210
2325
  for (const laneId of best.edge.lanes) {
2211
2326
  const lane = this.lanes.get(laneId);
2212
- if (lane.class === (wantRail ? "rail" : "walk")) lane.stops.push(stop);
2327
+ if (lane.class === wanted) lane.stops.push(stop);
2213
2328
  }
2214
2329
  });
2215
2330
  }
@@ -2297,7 +2412,8 @@ var TransportNetwork = class {
2297
2412
  road: 0,
2298
2413
  rail: 0,
2299
2414
  walk: 0,
2300
- air: 0
2415
+ air: 0,
2416
+ water: 0
2301
2417
  };
2302
2418
  for (const lane of this.lanes.values()) laneKm[lane.class] += lane.length / 1e3;
2303
2419
  let signals = 0;
@@ -2548,6 +2664,20 @@ const DEFAULT_POLICY = {
2548
2664
  perLaneKm: 0,
2549
2665
  max: 4
2550
2666
  },
2667
+ boat: {
2668
+ enabled: false,
2669
+ near: 100,
2670
+ far: 1800,
2671
+ keep: 2400,
2672
+ perLaneKm: .8,
2673
+ max: 12
2674
+ },
2675
+ marine: {
2676
+ accel: .25,
2677
+ brake: .5,
2678
+ gap: 12,
2679
+ headway: 8
2680
+ },
2551
2681
  driver: {
2552
2682
  accel: 1.6,
2553
2683
  brake: 2.8,
@@ -2601,7 +2731,8 @@ function policyForBudget(policy, budget) {
2601
2731
  car: ring(policy.car, budget.cars, scale),
2602
2732
  pedestrian: ring(policy.pedestrian, budget.pedestrians, walkScale),
2603
2733
  train: ring(policy.train, budget.trains, scale),
2604
- aircraft: ring(policy.aircraft, budget.aircraft, 1)
2734
+ aircraft: ring(policy.aircraft, budget.aircraft, 1),
2735
+ boat: ring(policy.boat, budget.boats, 1)
2605
2736
  };
2606
2737
  }
2607
2738
  //#endregion
@@ -2670,6 +2801,21 @@ const DEFAULT_TYPES = {
2670
2801
  height: 12,
2671
2802
  cruise: 110
2672
2803
  }],
2804
+ boat: [{
2805
+ id: "proxy.boat",
2806
+ length: 12,
2807
+ width: 4,
2808
+ height: 4,
2809
+ cruise: 5,
2810
+ waterway: "channel"
2811
+ }, {
2812
+ id: "proxy.ferry",
2813
+ length: 32,
2814
+ width: 9,
2815
+ height: 8,
2816
+ cruise: 8,
2817
+ waterway: "ferry"
2818
+ }],
2673
2819
  pedestrian: [
2674
2820
  {
2675
2821
  preset: "human.adult",
@@ -2853,6 +2999,10 @@ function outfitFor(preset, seed) {
2853
2999
  }
2854
3000
  /** Built-in templates: vehicles render through `ambient-vehicle`, pedestrians as figures. */
2855
3001
  const DEFAULT_TEMPLATES = {
3002
+ boat: (agent) => ({ renderable: {
3003
+ kind: "ambient-vehicle",
3004
+ ref: agent.type
3005
+ } }),
2856
3006
  car: (agent) => ({ renderable: {
2857
3007
  kind: "ambient-vehicle",
2858
3008
  ref: agent.type
@@ -2905,7 +3055,8 @@ const SPAWN_WEIGHT = {
2905
3055
  const LANE_CLASS = {
2906
3056
  car: "road",
2907
3057
  pedestrian: "walk",
2908
- train: "rail"
3058
+ train: "rail",
3059
+ boat: "water"
2909
3060
  };
2910
3061
  /** Resolve the observer from state, an entity, or the first `ambientObserver` entity. */
2911
3062
  function resolveObserver(world, state) {
@@ -2975,7 +3126,8 @@ function despawnAgents(world, env, observer) {
2975
3126
  car: [],
2976
3127
  pedestrian: [],
2977
3128
  train: [],
2978
- aircraft: []
3129
+ aircraft: [],
3130
+ boat: []
2979
3131
  };
2980
3132
  for (const [id, a, t] of world.query(AmbientAgent, Transform)) {
2981
3133
  if (a.consist !== void 0) {
@@ -3031,15 +3183,22 @@ function spawnAgents(world, env, observer, state) {
3031
3183
  car: 0,
3032
3184
  pedestrian: 0,
3033
3185
  train: 0,
3034
- aircraft: 0
3186
+ aircraft: 0,
3187
+ boat: 0
3035
3188
  };
3036
3189
  const occupancy = /* @__PURE__ */ new Map();
3037
3190
  for (const [, a] of world.query(AmbientAgent)) {
3038
3191
  if (a.consist === void 0) counts[a.kind]++;
3039
3192
  if (a.air !== void 0) continue;
3040
3193
  const list = occupancy.get(a.lane);
3041
- if (list === void 0) occupancy.set(a.lane, [a.s]);
3042
- else list.push(a.s);
3194
+ if (list === void 0) occupancy.set(a.lane, [{
3195
+ s: a.s,
3196
+ length: a.length
3197
+ }]);
3198
+ else list.push({
3199
+ s: a.s,
3200
+ length: a.length
3201
+ });
3043
3202
  }
3044
3203
  const ctx = {
3045
3204
  world,
@@ -3112,7 +3271,9 @@ function spawnOne(ctx, kind) {
3112
3271
  if (lane === void 0) continue;
3113
3272
  const seq = ctx.state.nextSeq;
3114
3273
  const seed = fmix32(seq ^ env.seed);
3115
- const vehicle = kind === "pedestrian" ? void 0 : pickWeighted(types, unit01(seed, 10));
3274
+ const available = kind === "boat" ? types.filter((t) => (t.waterway ?? "channel") === edge.kind && t.width <= edge.width / (edge.oneway ? 1 : 2) && t.length + 2 < lane.length) : types;
3275
+ if (kind === "boat" && available.length === 0) continue;
3276
+ const vehicle = kind === "pedestrian" ? void 0 : pickWeighted(available, unit01(seed, 10));
3116
3277
  const length = kind === "pedestrian" ? .5 : vehicle?.length ?? 4.5;
3117
3278
  const width = kind === "pedestrian" ? .5 : vehicle?.width ?? 1.8;
3118
3279
  const cars = kind === "train" ? dmath.max(1, vehicle?.cars ?? 2) : 1;
@@ -3128,10 +3289,10 @@ function spawnOne(ctx, kind) {
3128
3289
  if (observer.fx !== void 0 && observer.fz !== void 0 && distance < coneReach) {
3129
3290
  if ((dx * observer.fx + dz * observer.fz) / dmath.max(distance, 1e-6) > env.policy.forwardConeCos) continue;
3130
3291
  }
3131
- const minGap = kind === "train" ? 250 : kind === "pedestrian" ? 2.5 : length + env.policy.driver.gap + 8;
3292
+ const minGap = kind === "train" ? 250 : kind === "boat" ? length + env.policy.marine.gap + 30 : kind === "pedestrian" ? 2.5 : length + env.policy.driver.gap + 8;
3132
3293
  const clearLanes = kind === "train" ? edge.lanes : [lane.id];
3133
3294
  let clear = true;
3134
- for (const id of clearLanes) for (const other of ctx.occupancy.get(id) ?? []) if (dmath.abs(other - s) < minGap + behind) clear = false;
3295
+ for (const id of clearLanes) for (const other of ctx.occupancy.get(id) ?? []) if (dmath.abs(other.s - s) < (kind === "boat" ? (length + other.length) / 2 + env.policy.marine.gap + 30 : minGap + behind)) clear = false;
3135
3296
  if (!clear) continue;
3136
3297
  createLaneAgent(ctx, kind, lane, edge, s, seed, vehicle, length, width, cars);
3137
3298
  return true;
@@ -3155,14 +3316,15 @@ function createLaneAgent(ctx, kind, lane, edge, s, seed, vehicle, length, width,
3155
3316
  const palette = vehicle?.colors ?? (kind === "car" ? CAR_COLORS : void 0);
3156
3317
  const color = palette !== void 0 && palette.length > 0 ? palette[dmath.floor(unit01(seed, 11) * palette.length)] : void 0;
3157
3318
  const speed = kind === "pedestrian" ? 1.15 + .5 * unit01(seed, 2) : kind === "train" ? edge.speed * .5 : dmath.min(edge.speed * .7, vehicle?.cruise ?? edge.speed);
3158
- const next = chooseNext(lane, seed, 0);
3319
+ const next = kind === "boat" ? chooseVesselNext(env.net, lane, seed, 0, width, length) : chooseNext(lane, seed, 0);
3159
3320
  const agent = {
3160
3321
  kind,
3161
3322
  type,
3162
3323
  ...color !== void 0 ? { color } : {},
3163
3324
  lane: lane.id,
3164
3325
  s: q4(s),
3165
- speed: q4(speed),
3326
+ speed: q4(kind === "boat" ? dmath.min(speed, vehicle?.max ?? speed) : speed),
3327
+ ...kind === "boat" ? { cruise: dmath.min(vehicle?.cruise ?? edge.speed, vehicle?.max ?? 99) } : {},
3166
3328
  ...next !== void 0 ? { next } : {},
3167
3329
  seed,
3168
3330
  length,
@@ -3187,7 +3349,10 @@ function createLaneAgent(ctx, kind, lane, edge, s, seed, vehicle, length, width,
3187
3349
  seed: fmix32(seed + k)
3188
3350
  });
3189
3351
  }
3190
- ctx.occupancy.set(lane.id, [...ctx.occupancy.get(lane.id) ?? [], s]);
3352
+ ctx.occupancy.set(lane.id, [...ctx.occupancy.get(lane.id) ?? [], {
3353
+ s,
3354
+ length
3355
+ }]);
3191
3356
  }
3192
3357
  function spawnWithTemplate(ctx, id, agent) {
3193
3358
  const { env, world } = ctx;
@@ -3370,13 +3535,15 @@ function installAmbient(world, options = {}) {
3370
3535
  network.setClasses([
3371
3536
  ...classes.has("car") ? ["road"] : [],
3372
3537
  ...classes.has("pedestrian") ? ["walk"] : [],
3373
- ...classes.has("train") ? ["rail"] : []
3538
+ ...classes.has("train") ? ["rail"] : [],
3539
+ ...classes.has("boat") ? ["water"] : []
3374
3540
  ]);
3375
3541
  const base = mergePolicy(DEFAULT_POLICY, {
3376
3542
  car: { enabled: classes.has("car") },
3377
3543
  pedestrian: { enabled: classes.has("pedestrian") },
3378
3544
  train: { enabled: classes.has("train") },
3379
- aircraft: { enabled: classes.has("aircraft") }
3545
+ aircraft: { enabled: classes.has("aircraft") },
3546
+ boat: { enabled: classes.has("boat") }
3380
3547
  }, options.policy);
3381
3548
  const types = {
3382
3549
  ...DEFAULT_TYPES,
@@ -3386,7 +3553,8 @@ function installAmbient(world, options = {}) {
3386
3553
  "car",
3387
3554
  "train",
3388
3555
  "aircraft",
3389
- "pedestrian"
3556
+ "pedestrian",
3557
+ "boat"
3390
3558
  ]) if (types[kind].length === 0) types[kind] = DEFAULT_TYPES[kind];
3391
3559
  const templates = {};
3392
3560
  for (const kind of AMBIENT_KINDS) templates[kind] = options.templates?.[kind] !== void 0 ? options.templates[kind] ?? null : DEFAULT_TEMPLATES[kind];
@@ -3564,7 +3732,8 @@ function installAmbient(world, options = {}) {
3564
3732
  car: 0,
3565
3733
  pedestrian: 0,
3566
3734
  train: 0,
3567
- aircraft: 0
3735
+ aircraft: 0,
3736
+ boat: 0
3568
3737
  };
3569
3738
  let waiting = 0;
3570
3739
  for (const [, a] of world.query(AmbientAgent)) {
@@ -3706,6 +3875,7 @@ function ambientCapability(opts = {}) {
3706
3875
  ...car
3707
3876
  },
3708
3877
  ...density.pedestrian !== void 0 ? { pedestrian: { perLaneKm: density.pedestrian } } : {},
3878
+ ...density.boat !== void 0 ? { boat: { perLaneKm: density.boat } } : {},
3709
3879
  ...density.train !== void 0 ? { train: { perLaneKm: density.train } } : {},
3710
3880
  ...density.aircraft !== void 0 ? { aircraft: { max: density.aircraft } } : {}
3711
3881
  }
@@ -3760,6 +3930,10 @@ function networkToDocument(network, meta = {}, options = {}) {
3760
3930
  lanes: roadLanes,
3761
3931
  oneway: edge.oneway
3762
3932
  } : {},
3933
+ ...edge.class === "water" ? {
3934
+ oneway: edge.oneway,
3935
+ speed: edge.speed
3936
+ } : {},
3763
3937
  width: round(edge.width),
3764
3938
  ...edge.layer !== 0 ? { layer: edge.layer } : {},
3765
3939
  ...edge.bridge ? { bridge: true } : {},
@@ -3769,13 +3943,14 @@ function networkToDocument(network, meta = {}, options = {}) {
3769
3943
  for (const id of edge.lanes) {
3770
3944
  const lane = network.lane(id);
3771
3945
  for (const stop of lane?.stops ?? []) {
3772
- if (stop.kind !== "station" || seenStations.has(stop.id)) continue;
3946
+ if (stop.kind !== "station" && stop.kind !== "ferry" || seenStations.has(stop.id)) continue;
3773
3947
  seenStations.add(stop.id);
3774
- const sample = network.sampleLane(id, lane === void 0 ? 0 : stop.d - lane.trimStart);
3948
+ const sample = network.sampleLane(id, lane === void 0 ? 0 : laneCoordinate(lane, edge, stop.d));
3775
3949
  if (sample !== void 0) stations.push({
3776
3950
  id: stop.id,
3777
3951
  at: [round(sample.x), round(sample.z)],
3778
- kind: "rail"
3952
+ kind: stop.kind === "ferry" ? "ferry" : "rail",
3953
+ ...stop.dwell !== void 0 ? { dwell: stop.dwell } : {}
3779
3954
  });
3780
3955
  }
3781
3956
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bendyline/molen-ambient",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -42,14 +42,14 @@
42
42
  ],
43
43
  "dependencies": {
44
44
  "zod": "^4.6.5",
45
- "@bendyline/molen-figures": "0.0.7",
46
- "@bendyline/molen-kernel": "0.0.5",
47
- "@bendyline/molen-schema": "0.0.5",
48
- "@bendyline/molen-terrain": "0.0.8"
45
+ "@bendyline/molen-figures": "0.0.9",
46
+ "@bendyline/molen-schema": "0.0.7",
47
+ "@bendyline/molen-kernel": "0.0.7",
48
+ "@bendyline/molen-terrain": "0.0.10"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "three": ">=0.184.0 <0.187.0",
52
- "@bendyline/molen-client": "0.0.7"
52
+ "@bendyline/molen-client": "0.0.9"
53
53
  },
54
54
  "peerDependenciesMeta": {
55
55
  "@bendyline/molen-client": {
@@ -67,7 +67,7 @@
67
67
  "tsdown": "^0.22.2",
68
68
  "typescript": "^6.0.3",
69
69
  "vitest": "^5.0.1",
70
- "@bendyline/molen-client": "0.0.7"
70
+ "@bendyline/molen-client": "0.0.9"
71
71
  },
72
72
  "scripts": {
73
73
  "build": "tsdown",