@bendyline/molen-ambient 0.0.9 → 0.0.11

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/kernel.mjs CHANGED
@@ -1,7 +1,8 @@
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";
5
+ import { z } from "zod";
5
6
  import { PATH_SURFACE_LIFT, ROAD_SURFACE_LIFT, bridgeDeckHeightFn, lineSegmentIndex, sampleTerrainLine } from "@bendyline/molen-terrain/kernel";
6
7
  //#region src/kernel/agents/idm.ts
7
8
  /** Intelligent Driver Model: acceleration from speed, desired speed and the gap to a leader. */
@@ -199,7 +200,7 @@ function laneSample() {
199
200
  * the next tick and a keyframe restores exactly.
200
201
  *
201
202
  * Order: gather → occupancy → armed crossings → junction grants → cars → pedestrians → trains
202
- * (leads, then their cars) → aircraft → write changed agents and transforms.
203
+ * (leads, then their cars) → vessels → aircraft → write changed agents and transforms.
203
204
  */
204
205
  const TURN_SPEED = {
205
206
  left: 7,
@@ -231,6 +232,18 @@ function chooseNext(lane, seed, hops) {
231
232
  }
232
233
  return moves[moves.length - 1].to;
233
234
  }
235
+ /** Reject branches narrower/shorter than a vessel before choosing a seeded turn. */
236
+ function chooseVesselNext(net, lane, seed, hops, width, length) {
237
+ const next = lane.next.filter((move) => {
238
+ const target = net.lane(move.to);
239
+ const edge = target !== void 0 ? net.edge(target.edge) : void 0;
240
+ return edge !== void 0 && target !== void 0 && width <= edge.width / (edge.oneway ? 1 : 2) && length + 2 < target.length;
241
+ });
242
+ return chooseNext({
243
+ ...lane,
244
+ next
245
+ }, seed, hops);
246
+ }
234
247
  /** Where an agent is: its lane body, or the connector curve into its lane. */
235
248
  function agentSample(net, agent, out) {
236
249
  if (agent.air !== void 0) {
@@ -321,6 +334,7 @@ function stepAgents(world, env) {
321
334
  for (const ref of refs) {
322
335
  if (ref.lane === void 0 || ref.edge === void 0) continue;
323
336
  if (ref.a.kind === "car") stepRoad(ref, occupancy, granted, armed, env);
337
+ else if (ref.a.kind === "boat") stepVessel(ref, occupancy, env);
324
338
  else if (ref.a.kind === "pedestrian") stepWalker(ref, occupancy, env);
325
339
  else if (ref.a.kind === "train" && ref.a.consist === void 0) stepTrainLead(ref, occupancy, env, consistSize.get(ref.id) ?? 0);
326
340
  }
@@ -394,7 +408,8 @@ function advanceLanes(ref, env) {
394
408
  w.prev = lane.id;
395
409
  w.lane = nextLane.id;
396
410
  w.hops += 1;
397
- const chosen = chooseNext(nextLane, w.seed, w.hops);
411
+ const chosen = w.kind === "boat" ? chooseVesselNext(net, nextLane, w.seed, w.hops, w.width, w.length) : chooseNext(nextLane, w.seed, w.hops);
412
+ if (w.kind === "boat") delete w.served;
398
413
  if (chosen === void 0) delete w.next;
399
414
  else w.next = chosen;
400
415
  lane = nextLane;
@@ -864,6 +879,77 @@ function reverseConsist(ref, env, cars) {
864
879
  ref.edge = net.edge(headLane.edge);
865
880
  delete w.served;
866
881
  }
882
+ /** Kinematic water navigation: slow acceleration, following gaps and scheduled dock dwell. */
883
+ function stepVessel(ref, occupancy, env) {
884
+ const { a, w } = ref;
885
+ const { net, dt, tick, tickRate } = env;
886
+ const lane = ref.lane;
887
+ const edge = ref.edge;
888
+ const p = env.policy.marine;
889
+ if (a.state === "dwell") {
890
+ const stop = lane.stops.find((s) => s.id === a.served);
891
+ if (tick - a.since < (stop?.dwell ?? 30) * tickRate) {
892
+ w.speed = 0;
893
+ return;
894
+ }
895
+ }
896
+ const move = net.movement(a.lane, a.next ?? "");
897
+ let v0 = dmath.min(edge.speed, a.cruise ?? edge.speed);
898
+ if (move?.turn === "uturn" && lane.length - a.s < a.length + 20) v0 = dmath.min(v0, 1.5);
899
+ if (a.s < 0) v0 = dmath.min(v0, 2.5);
900
+ let limit = Number.POSITIVE_INFINITY;
901
+ let gap = Number.POSITIVE_INFINITY;
902
+ let leaderSpeed = 0;
903
+ const leader = leaderOnLane(ref, occupancy);
904
+ if (leader !== void 0) {
905
+ gap = leader.a.s - a.s - (a.length + leader.a.length) / 2;
906
+ limit = leader.a.s - (a.length + leader.a.length) / 2 - p.gap;
907
+ leaderSpeed = leader.a.speed;
908
+ } else if (a.next !== void 0 && move !== void 0) {
909
+ const next = firstOnLane(a.next, occupancy);
910
+ if (next !== void 0) {
911
+ gap = lane.length - a.s + move.length + next.a.s - (a.length + next.a.length) / 2;
912
+ limit = a.s + gap - p.gap;
913
+ leaderSpeed = next.a.speed;
914
+ }
915
+ } else {
916
+ limit = lane.length - a.length / 2;
917
+ gap = limit - a.s + p.gap;
918
+ }
919
+ let dock;
920
+ if (edge.kind === "ferry") {
921
+ for (const stop of lane.stops) {
922
+ if (stop.kind !== "ferry" || stop.id === a.served) continue;
923
+ const at = laneCoordinate(lane, edge, stop.d);
924
+ if (at >= a.s - .1 && (dock === void 0 || at < dock.at)) dock = {
925
+ at,
926
+ id: stop.id
927
+ };
928
+ }
929
+ if (dock === void 0 && move?.turn === "uturn" && a.served !== `end:${lane.id}`) dock = {
930
+ at: lane.length,
931
+ id: `end:${lane.id}`
932
+ };
933
+ }
934
+ if (dock !== void 0 && dock.at - a.s + p.gap < gap) {
935
+ gap = dock.at - a.s + p.gap;
936
+ leaderSpeed = 0;
937
+ limit = dmath.min(limit, dock.at);
938
+ }
939
+ const accel = idmAcceleration(a.speed, v0, gap, a.speed - leaderSpeed, p);
940
+ w.speed = dmath.max(0, a.speed + accel * dt);
941
+ w.s = dmath.min(a.s + w.speed * dt, dmath.max(a.s, limit));
942
+ if (w.s >= limit) w.speed = dmath.min(w.speed, leaderSpeed);
943
+ if (dock !== void 0 && dmath.abs(w.s - dock.at) < .5 && w.speed < .3) {
944
+ w.s = dock.at;
945
+ w.speed = 0;
946
+ w.served = dock.id;
947
+ setState(w, "dwell", tick);
948
+ return;
949
+ }
950
+ advanceLanes(ref, env);
951
+ setState(w, w.speed < .05 ? "wait" : "move", tick);
952
+ }
867
953
  function stepAircraft(ref, env) {
868
954
  const { w } = ref;
869
955
  w.s = ref.a.s + ref.a.speed * env.dt;
@@ -1043,6 +1129,7 @@ function rebuildNodeGroup(store, nodeIds) {
1043
1129
  const cache = new EndCache(store);
1044
1130
  buildRoadMovements(store, cache, roadArms, junction);
1045
1131
  buildRailMovements(store, cache, armsOf(store, group, "rail"));
1132
+ buildWaterMovements(store, cache, armsOf(store, group, "water"));
1046
1133
  buildWalkMovements(store, cache, armsOf(store, group, "walk"), roadArms, junction, maxWidth);
1047
1134
  }
1048
1135
  function buildJunction(store, id, group, arms, radius) {
@@ -1259,6 +1346,27 @@ function buildRoadMovements(store, cache, arms, junction) {
1259
1346
  }
1260
1347
  });
1261
1348
  }
1349
+ /** Keep ferry services separate from navigation channels even where their lines intersect. */
1350
+ function buildWaterMovements(store, cache, arms) {
1351
+ for (const inArm of arms) for (const lane of lanesAt(store, inArm, "water", true)) {
1352
+ const moves = [];
1353
+ for (const outArm of arms) {
1354
+ if (outArm === inArm || outArm.edge.kind !== inArm.edge.kind) continue;
1355
+ for (const target of lanesAt(store, outArm, "water", false)) {
1356
+ const move = movement(cache, lane, target, "straight", 1, void 0, 0);
1357
+ if (move !== void 0) moves.push(move);
1358
+ }
1359
+ }
1360
+ if (moves.length === 0) {
1361
+ const back = lanesAt(store, inArm, "water", false)[0];
1362
+ if (back !== void 0) {
1363
+ const move = movement(cache, lane, back, "uturn", 1, void 0, 0);
1364
+ if (move !== void 0) moves.push(move);
1365
+ }
1366
+ }
1367
+ lane.next = moves;
1368
+ }
1369
+ }
1262
1370
  function buildRailMovements(store, cache, arms) {
1263
1371
  for (const inArm of arms) for (const lane of lanesAt(store, inArm, "rail", true)) {
1264
1372
  const moves = [];
@@ -1343,7 +1451,8 @@ const CLASS_INDEX = {
1343
1451
  road: 0,
1344
1452
  rail: 1,
1345
1453
  walk: 2,
1346
- air: 3
1454
+ air: 3,
1455
+ water: 4
1347
1456
  };
1348
1457
  /** Cumulative distances of a polyline. */
1349
1458
  function cumulative(points) {
@@ -1432,12 +1541,7 @@ function planarSplit(drafts, options = {}) {
1432
1541
  }
1433
1542
  }
1434
1543
  const nodes = [];
1435
- const nodeCells = [
1436
- /* @__PURE__ */ new Map(),
1437
- /* @__PURE__ */ new Map(),
1438
- /* @__PURE__ */ new Map(),
1439
- /* @__PURE__ */ new Map()
1440
- ];
1544
+ const nodeCells = Object.keys(CLASS_INDEX).map(() => /* @__PURE__ */ new Map());
1441
1545
  const nodeAt = (x, z, draft) => {
1442
1546
  const cx = dmath.floor(x / snap);
1443
1547
  const cz = dmath.floor(z / snap);
@@ -1614,7 +1718,8 @@ const CLASSES = [
1614
1718
  "road",
1615
1719
  "rail",
1616
1720
  "walk",
1617
- "air"
1721
+ "air",
1722
+ "water"
1618
1723
  ];
1619
1724
  var LaneGrid = class {
1620
1725
  cells = /* @__PURE__ */ new Map();
@@ -1648,7 +1753,8 @@ var LaneGrid = class {
1648
1753
  road: 0,
1649
1754
  rail: 0,
1650
1755
  walk: 0,
1651
- air: 0
1756
+ air: 0,
1757
+ water: 0
1652
1758
  }
1653
1759
  };
1654
1760
  this.cells.set(key, cell);
@@ -1664,7 +1770,8 @@ var LaneGrid = class {
1664
1770
  road: 0,
1665
1771
  rail: 0,
1666
1772
  walk: 0,
1667
- air: 0
1773
+ air: 0,
1774
+ water: 0
1668
1775
  };
1669
1776
  for (const cls of CLASSES) {
1670
1777
  const m = (d1 - d0) * laneCounts[cls];
@@ -1789,7 +1896,8 @@ var TransportNetwork = class {
1789
1896
  "road",
1790
1897
  "rail",
1791
1898
  "walk",
1792
- "air"
1899
+ "air",
1900
+ "water"
1793
1901
  ]);
1794
1902
  }
1795
1903
  /** Change which lane classes are built (applies to tiles registered afterwards). */
@@ -2013,6 +2121,7 @@ var TransportNetwork = class {
2013
2121
  if (dense.heights !== void 0) dense.heights.forEach((h, i) => {
2014
2122
  ys[i] = h;
2015
2123
  });
2124
+ else if (draft.class === "water") ys.fill(0);
2016
2125
  else if (draft.bridge || draft.bridgeConnections?.length) {
2017
2126
  const deck = bridgeDeckHeightFn(path, heightAt, {
2018
2127
  ...draft.deckElevation !== void 0 ? { deckElevation: draft.deckElevation } : {},
@@ -2062,7 +2171,8 @@ var TransportNetwork = class {
2062
2171
  road: 0,
2063
2172
  rail: 0,
2064
2173
  walk: 0,
2065
- air: 0
2174
+ air: 0,
2175
+ water: 0
2066
2176
  };
2067
2177
  for (const laneId of edge.lanes) counts[this.lanes.get(laneId).class]++;
2068
2178
  this.grid.insert(edge, counts);
@@ -2124,6 +2234,9 @@ var TransportNetwork = class {
2124
2234
  make("sl+", "walk", 1, 1, -o + side * .35, SIDEWALK_LIFT);
2125
2235
  make("sl-", "walk", -1, 1, o + side * .35, SIDEWALK_LIFT);
2126
2236
  }
2237
+ } else if (draft.class === "water") {
2238
+ make("f0", "water", 1, 0, draft.oneway ? 0 : draft.width / 4);
2239
+ if (!draft.oneway) make("b0", "water", -1, 0, draft.width / 4);
2127
2240
  } else if (draft.class === "rail") {
2128
2241
  make("f0", "rail", 1, 0, 0);
2129
2242
  make("b0", "rail", -1, 0, 0);
@@ -2186,13 +2299,16 @@ var TransportNetwork = class {
2186
2299
  record.pois.forEach((poi, i) => {
2187
2300
  const wantRail = poi.kind === "station" || poi.kind === "tram_stop";
2188
2301
  const wantWalk = poi.kind === "bus_stop";
2189
- if (!wantRail && !wantWalk) return;
2190
- const reach = wantRail ? 25 : 12;
2302
+ const wantWater = poi.kind === "ferry_terminal";
2303
+ if (!wantRail && !wantWalk && !wantWater) return;
2304
+ const wanted = wantWater ? "water" : wantRail ? "rail" : "walk";
2305
+ const reach = wantWater ? 80 : wantRail ? 25 : 12;
2191
2306
  let best;
2192
2307
  for (const edgeId of this.grid.edgesNear(poi.x, poi.z, reach)) {
2193
2308
  if (!own.has(edgeId)) continue;
2194
2309
  const edge = this.edges.get(edgeId);
2195
- if (!edge.lanes.some((l) => this.lanes.get(l)?.class === (wantRail ? "rail" : "walk"))) continue;
2310
+ if (wantWater && edge.kind !== "ferry") continue;
2311
+ if (!edge.lanes.some((l) => this.lanes.get(l)?.class === wanted)) continue;
2196
2312
  const hit = projectOnPath(edge.path, poi.x, poi.z);
2197
2313
  if (hit.distance <= reach && (best === void 0 || hit.distance < best.distance)) best = {
2198
2314
  edge,
@@ -2203,13 +2319,13 @@ var TransportNetwork = class {
2203
2319
  if (best === void 0) return;
2204
2320
  const stop = {
2205
2321
  d: best.d,
2206
- kind: wantRail ? "station" : "bus",
2322
+ kind: wantWater ? "ferry" : wantRail ? "station" : "bus",
2207
2323
  id: `${record.key}:${poi.kind}:${i}`,
2208
2324
  ...poi.dwell !== void 0 ? { dwell: poi.dwell } : {}
2209
2325
  };
2210
2326
  for (const laneId of best.edge.lanes) {
2211
2327
  const lane = this.lanes.get(laneId);
2212
- if (lane.class === (wantRail ? "rail" : "walk")) lane.stops.push(stop);
2328
+ if (lane.class === wanted) lane.stops.push(stop);
2213
2329
  }
2214
2330
  });
2215
2331
  }
@@ -2297,7 +2413,8 @@ var TransportNetwork = class {
2297
2413
  road: 0,
2298
2414
  rail: 0,
2299
2415
  walk: 0,
2300
- air: 0
2416
+ air: 0,
2417
+ water: 0
2301
2418
  };
2302
2419
  for (const lane of this.lanes.values()) laneKm[lane.class] += lane.length / 1e3;
2303
2420
  let signals = 0;
@@ -2548,6 +2665,20 @@ const DEFAULT_POLICY = {
2548
2665
  perLaneKm: 0,
2549
2666
  max: 4
2550
2667
  },
2668
+ boat: {
2669
+ enabled: false,
2670
+ near: 100,
2671
+ far: 1800,
2672
+ keep: 2400,
2673
+ perLaneKm: .8,
2674
+ max: 12
2675
+ },
2676
+ marine: {
2677
+ accel: .25,
2678
+ brake: .5,
2679
+ gap: 12,
2680
+ headway: 8
2681
+ },
2551
2682
  driver: {
2552
2683
  accel: 1.6,
2553
2684
  brake: 2.8,
@@ -2601,7 +2732,8 @@ function policyForBudget(policy, budget) {
2601
2732
  car: ring(policy.car, budget.cars, scale),
2602
2733
  pedestrian: ring(policy.pedestrian, budget.pedestrians, walkScale),
2603
2734
  train: ring(policy.train, budget.trains, scale),
2604
- aircraft: ring(policy.aircraft, budget.aircraft, 1)
2735
+ aircraft: ring(policy.aircraft, budget.aircraft, 1),
2736
+ boat: ring(policy.boat, budget.boats, 1)
2605
2737
  };
2606
2738
  }
2607
2739
  //#endregion
@@ -2670,6 +2802,21 @@ const DEFAULT_TYPES = {
2670
2802
  height: 12,
2671
2803
  cruise: 110
2672
2804
  }],
2805
+ boat: [{
2806
+ id: "proxy.boat",
2807
+ length: 12,
2808
+ width: 4,
2809
+ height: 4,
2810
+ cruise: 5,
2811
+ waterway: "channel"
2812
+ }, {
2813
+ id: "proxy.ferry",
2814
+ length: 32,
2815
+ width: 9,
2816
+ height: 8,
2817
+ cruise: 8,
2818
+ waterway: "ferry"
2819
+ }],
2673
2820
  pedestrian: [
2674
2821
  {
2675
2822
  preset: "human.adult",
@@ -2853,6 +3000,10 @@ function outfitFor(preset, seed) {
2853
3000
  }
2854
3001
  /** Built-in templates: vehicles render through `ambient-vehicle`, pedestrians as figures. */
2855
3002
  const DEFAULT_TEMPLATES = {
3003
+ boat: (agent) => ({ renderable: {
3004
+ kind: "ambient-vehicle",
3005
+ ref: agent.type
3006
+ } }),
2856
3007
  car: (agent) => ({ renderable: {
2857
3008
  kind: "ambient-vehicle",
2858
3009
  ref: agent.type
@@ -2905,7 +3056,8 @@ const SPAWN_WEIGHT = {
2905
3056
  const LANE_CLASS = {
2906
3057
  car: "road",
2907
3058
  pedestrian: "walk",
2908
- train: "rail"
3059
+ train: "rail",
3060
+ boat: "water"
2909
3061
  };
2910
3062
  /** Resolve the observer from state, an entity, or the first `ambientObserver` entity. */
2911
3063
  function resolveObserver(world, state) {
@@ -2975,7 +3127,8 @@ function despawnAgents(world, env, observer) {
2975
3127
  car: [],
2976
3128
  pedestrian: [],
2977
3129
  train: [],
2978
- aircraft: []
3130
+ aircraft: [],
3131
+ boat: []
2979
3132
  };
2980
3133
  for (const [id, a, t] of world.query(AmbientAgent, Transform)) {
2981
3134
  if (a.consist !== void 0) {
@@ -3031,15 +3184,22 @@ function spawnAgents(world, env, observer, state) {
3031
3184
  car: 0,
3032
3185
  pedestrian: 0,
3033
3186
  train: 0,
3034
- aircraft: 0
3187
+ aircraft: 0,
3188
+ boat: 0
3035
3189
  };
3036
3190
  const occupancy = /* @__PURE__ */ new Map();
3037
3191
  for (const [, a] of world.query(AmbientAgent)) {
3038
3192
  if (a.consist === void 0) counts[a.kind]++;
3039
3193
  if (a.air !== void 0) continue;
3040
3194
  const list = occupancy.get(a.lane);
3041
- if (list === void 0) occupancy.set(a.lane, [a.s]);
3042
- else list.push(a.s);
3195
+ if (list === void 0) occupancy.set(a.lane, [{
3196
+ s: a.s,
3197
+ length: a.length
3198
+ }]);
3199
+ else list.push({
3200
+ s: a.s,
3201
+ length: a.length
3202
+ });
3043
3203
  }
3044
3204
  const ctx = {
3045
3205
  world,
@@ -3112,7 +3272,9 @@ function spawnOne(ctx, kind) {
3112
3272
  if (lane === void 0) continue;
3113
3273
  const seq = ctx.state.nextSeq;
3114
3274
  const seed = fmix32(seq ^ env.seed);
3115
- const vehicle = kind === "pedestrian" ? void 0 : pickWeighted(types, unit01(seed, 10));
3275
+ 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;
3276
+ if (kind === "boat" && available.length === 0) continue;
3277
+ const vehicle = kind === "pedestrian" ? void 0 : pickWeighted(available, unit01(seed, 10));
3116
3278
  const length = kind === "pedestrian" ? .5 : vehicle?.length ?? 4.5;
3117
3279
  const width = kind === "pedestrian" ? .5 : vehicle?.width ?? 1.8;
3118
3280
  const cars = kind === "train" ? dmath.max(1, vehicle?.cars ?? 2) : 1;
@@ -3128,10 +3290,10 @@ function spawnOne(ctx, kind) {
3128
3290
  if (observer.fx !== void 0 && observer.fz !== void 0 && distance < coneReach) {
3129
3291
  if ((dx * observer.fx + dz * observer.fz) / dmath.max(distance, 1e-6) > env.policy.forwardConeCos) continue;
3130
3292
  }
3131
- const minGap = kind === "train" ? 250 : kind === "pedestrian" ? 2.5 : length + env.policy.driver.gap + 8;
3293
+ const minGap = kind === "train" ? 250 : kind === "boat" ? length + env.policy.marine.gap + 30 : kind === "pedestrian" ? 2.5 : length + env.policy.driver.gap + 8;
3132
3294
  const clearLanes = kind === "train" ? edge.lanes : [lane.id];
3133
3295
  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;
3296
+ 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
3297
  if (!clear) continue;
3136
3298
  createLaneAgent(ctx, kind, lane, edge, s, seed, vehicle, length, width, cars);
3137
3299
  return true;
@@ -3155,14 +3317,15 @@ function createLaneAgent(ctx, kind, lane, edge, s, seed, vehicle, length, width,
3155
3317
  const palette = vehicle?.colors ?? (kind === "car" ? CAR_COLORS : void 0);
3156
3318
  const color = palette !== void 0 && palette.length > 0 ? palette[dmath.floor(unit01(seed, 11) * palette.length)] : void 0;
3157
3319
  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);
3320
+ const next = kind === "boat" ? chooseVesselNext(env.net, lane, seed, 0, width, length) : chooseNext(lane, seed, 0);
3159
3321
  const agent = {
3160
3322
  kind,
3161
3323
  type,
3162
3324
  ...color !== void 0 ? { color } : {},
3163
3325
  lane: lane.id,
3164
3326
  s: q4(s),
3165
- speed: q4(speed),
3327
+ speed: q4(kind === "boat" ? dmath.min(speed, vehicle?.max ?? speed) : speed),
3328
+ ...kind === "boat" ? { cruise: dmath.min(vehicle?.cruise ?? edge.speed, vehicle?.max ?? 99) } : {},
3166
3329
  ...next !== void 0 ? { next } : {},
3167
3330
  seed,
3168
3331
  length,
@@ -3187,7 +3350,10 @@ function createLaneAgent(ctx, kind, lane, edge, s, seed, vehicle, length, width,
3187
3350
  seed: fmix32(seed + k)
3188
3351
  });
3189
3352
  }
3190
- ctx.occupancy.set(lane.id, [...ctx.occupancy.get(lane.id) ?? [], s]);
3353
+ ctx.occupancy.set(lane.id, [...ctx.occupancy.get(lane.id) ?? [], {
3354
+ s,
3355
+ length
3356
+ }]);
3191
3357
  }
3192
3358
  function spawnWithTemplate(ctx, id, agent) {
3193
3359
  const { env, world } = ctx;
@@ -3370,13 +3536,15 @@ function installAmbient(world, options = {}) {
3370
3536
  network.setClasses([
3371
3537
  ...classes.has("car") ? ["road"] : [],
3372
3538
  ...classes.has("pedestrian") ? ["walk"] : [],
3373
- ...classes.has("train") ? ["rail"] : []
3539
+ ...classes.has("train") ? ["rail"] : [],
3540
+ ...classes.has("boat") ? ["water"] : []
3374
3541
  ]);
3375
3542
  const base = mergePolicy(DEFAULT_POLICY, {
3376
3543
  car: { enabled: classes.has("car") },
3377
3544
  pedestrian: { enabled: classes.has("pedestrian") },
3378
3545
  train: { enabled: classes.has("train") },
3379
- aircraft: { enabled: classes.has("aircraft") }
3546
+ aircraft: { enabled: classes.has("aircraft") },
3547
+ boat: { enabled: classes.has("boat") }
3380
3548
  }, options.policy);
3381
3549
  const types = {
3382
3550
  ...DEFAULT_TYPES,
@@ -3386,7 +3554,8 @@ function installAmbient(world, options = {}) {
3386
3554
  "car",
3387
3555
  "train",
3388
3556
  "aircraft",
3389
- "pedestrian"
3557
+ "pedestrian",
3558
+ "boat"
3390
3559
  ]) if (types[kind].length === 0) types[kind] = DEFAULT_TYPES[kind];
3391
3560
  const templates = {};
3392
3561
  for (const kind of AMBIENT_KINDS) templates[kind] = options.templates?.[kind] !== void 0 ? options.templates[kind] ?? null : DEFAULT_TEMPLATES[kind];
@@ -3564,7 +3733,8 @@ function installAmbient(world, options = {}) {
3564
3733
  car: 0,
3565
3734
  pedestrian: 0,
3566
3735
  train: 0,
3567
- aircraft: 0
3736
+ aircraft: 0,
3737
+ boat: 0
3568
3738
  };
3569
3739
  let waiting = 0;
3570
3740
  for (const [, a] of world.query(AmbientAgent)) {
@@ -3706,6 +3876,7 @@ function ambientCapability(opts = {}) {
3706
3876
  ...car
3707
3877
  },
3708
3878
  ...density.pedestrian !== void 0 ? { pedestrian: { perLaneKm: density.pedestrian } } : {},
3879
+ ...density.boat !== void 0 ? { boat: { perLaneKm: density.boat } } : {},
3709
3880
  ...density.train !== void 0 ? { train: { perLaneKm: density.train } } : {},
3710
3881
  ...density.aircraft !== void 0 ? { aircraft: { max: density.aircraft } } : {}
3711
3882
  }
@@ -3760,6 +3931,10 @@ function networkToDocument(network, meta = {}, options = {}) {
3760
3931
  lanes: roadLanes,
3761
3932
  oneway: edge.oneway
3762
3933
  } : {},
3934
+ ...edge.class === "water" ? {
3935
+ oneway: edge.oneway,
3936
+ speed: edge.speed
3937
+ } : {},
3763
3938
  width: round(edge.width),
3764
3939
  ...edge.layer !== 0 ? { layer: edge.layer } : {},
3765
3940
  ...edge.bridge ? { bridge: true } : {},
@@ -3769,13 +3944,14 @@ function networkToDocument(network, meta = {}, options = {}) {
3769
3944
  for (const id of edge.lanes) {
3770
3945
  const lane = network.lane(id);
3771
3946
  for (const stop of lane?.stops ?? []) {
3772
- if (stop.kind !== "station" || seenStations.has(stop.id)) continue;
3947
+ if (stop.kind !== "station" && stop.kind !== "ferry" || seenStations.has(stop.id)) continue;
3773
3948
  seenStations.add(stop.id);
3774
- const sample = network.sampleLane(id, lane === void 0 ? 0 : stop.d - lane.trimStart);
3949
+ const sample = network.sampleLane(id, lane === void 0 ? 0 : laneCoordinate(lane, edge, stop.d));
3775
3950
  if (sample !== void 0) stations.push({
3776
3951
  id: stop.id,
3777
3952
  at: [round(sample.x), round(sample.z)],
3778
- kind: "rail"
3953
+ kind: stop.kind === "ferry" ? "ferry" : "rail",
3954
+ ...stop.dwell !== void 0 ? { dwell: stop.dwell } : {}
3779
3955
  });
3780
3956
  }
3781
3957
  }
@@ -3799,7 +3975,186 @@ function networkToDocument(network, meta = {}, options = {}) {
3799
3975
  };
3800
3976
  }
3801
3977
  //#endregion
3978
+ //#region src/kernel/wildlife.ts
3979
+ /** Bounded, fixed-step ambient wildlife. No global randomness, timers, geography or renderer. */
3980
+ const WILDLIFE_TICK_RATE = 20;
3981
+ const WILDLIFE_CELL_METERS = 96;
3982
+ function suitable(species, habitat) {
3983
+ return habitat?.safe === true && Number.isFinite(habitat.height) && (species.motion === "fly" || (species.motion === "swim" ? habitat.water : !habitat.water));
3984
+ }
3985
+ function heightFor(species, habitat) {
3986
+ return habitat.height + (species.motion === "fly" ? species.clearance : species.motion === "swim" ? -species.clearance : 0);
3987
+ }
3988
+ /** Stable world-grid candidates. Adding an unrelated species does not reroll an existing one. */
3989
+ function wildlifeCandidates(world, observer, budget, tick = 0) {
3990
+ const radius = Math.max(0, Math.min(2e3, budget.radius));
3991
+ const density = dmath.clamp(budget.density, 0, 1);
3992
+ const limit = Math.max(0, Math.min(256, Math.floor(budget.animals)));
3993
+ if (limit === 0 || density === 0 || !observer.every(Number.isFinite)) return [];
3994
+ const size = 96;
3995
+ const found = [];
3996
+ for (let row = Math.floor((observer[2] - radius) / size); row <= Math.floor((observer[2] + radius) / size); row++) for (let column = Math.floor((observer[0] - radius) / size); column <= Math.floor((observer[0] + radius) / size); column++) {
3997
+ const choices = world.choices((column + .5) * size, (row + .5) * size);
3998
+ for (const choice of choices) {
3999
+ const species = choice.species;
4000
+ const id = `${species.id}@${species.version}/${column}/${row}`;
4001
+ const seed = fnv1a(id);
4002
+ if (unit01(seed, 0) >= Math.min(1, choice.density * size * size / 1e6) * density) continue;
4003
+ const x = q4((column + .15 + unit01(seed, 1) * .7) * size);
4004
+ const z = q4((row + .15 + unit01(seed, 2) * .7) * size);
4005
+ const distance = (x - observer[0]) ** 2 + (z - observer[2]) ** 2;
4006
+ if (distance > radius * radius) continue;
4007
+ const actual = world.choices(x, z).find((entry) => entry.species.id === species.id);
4008
+ if (actual === void 0 || unit01(seed, 0) >= Math.min(1, actual.density * size * size / 1e6) * density) continue;
4009
+ const habitat = world.habitat(x, z, species.margin);
4010
+ if (!suitable(species, habitat) || !actual.habitats.includes(habitat.kind)) continue;
4011
+ const y = heightFor(species, habitat);
4012
+ if ((y - observer[1]) ** 2 + distance > radius * radius) continue;
4013
+ found.push({
4014
+ distance,
4015
+ agent: {
4016
+ id,
4017
+ species: species.id,
4018
+ seed,
4019
+ anchor: [x, z],
4020
+ position: [
4021
+ x,
4022
+ q4(y),
4023
+ z
4024
+ ],
4025
+ target: [x, z],
4026
+ heading: unit01(seed, 3) * dmath.PI * 2,
4027
+ speed: 0,
4028
+ since: tick,
4029
+ nextDecision: tick,
4030
+ decisions: 0,
4031
+ phase: unit01(seed, 4)
4032
+ }
4033
+ });
4034
+ }
4035
+ }
4036
+ return found.sort((a, b) => a.distance - b.distance || (a.agent.id < b.agent.id ? -1 : 1)).slice(0, limit).map(({ agent }) => agent);
4037
+ }
4038
+ /** Advance one 1/20-second step. A host can snapshot these plain records without hidden state. */
4039
+ function stepWildlife(agents, speciesById, world, tick) {
4040
+ const next = [];
4041
+ for (const previous of agents) {
4042
+ const species = speciesById.get(previous.species);
4043
+ if (species === void 0) continue;
4044
+ const start = world.habitat(previous.position[0], previous.position[2], species.margin);
4045
+ const currentChoice = world.choices(previous.position[0], previous.position[2]).find((choice) => choice.species.id === species.id);
4046
+ if (!suitable(species, start) || currentChoice === void 0 || !currentChoice.habitats.includes(start.kind)) continue;
4047
+ const agent = {
4048
+ ...previous,
4049
+ position: [...previous.position],
4050
+ target: [...previous.target]
4051
+ };
4052
+ if (tick >= agent.nextDecision) {
4053
+ const stream = 10 + agent.decisions++ * 4;
4054
+ const angle = unit01(agent.seed, stream) * dmath.PI * 2;
4055
+ const radius = species.roam * dmath.sqrt(unit01(agent.seed, stream + 1));
4056
+ agent.target = species.motion !== "fly" && species.motion !== "swim" && unit01(agent.seed, stream + 2) < species.rest ? [agent.position[0], agent.position[2]] : [q4(agent.anchor[0] + dmath.cos(angle) * radius), q4(agent.anchor[1] + dmath.sin(angle) * radius)];
4057
+ agent.nextDecision = tick + Math.floor((4 + unit01(agent.seed, stream + 3) * 8) * 20);
4058
+ agent.since = tick;
4059
+ }
4060
+ const dx = agent.target[0] - agent.position[0];
4061
+ const dz = agent.target[1] - agent.position[2];
4062
+ const distance = dmath.sqrt(dx * dx + dz * dz);
4063
+ const travel = Math.min(distance, species.speed / 20);
4064
+ agent.speed = 0;
4065
+ if (distance > .01) {
4066
+ const x = q4(agent.position[0] + dx / distance * travel);
4067
+ const z = q4(agent.position[2] + dz / distance * travel);
4068
+ const steps = Math.max(1, Math.ceil(travel / Math.max(.1, species.margin)));
4069
+ let destination;
4070
+ for (let i = 1; i <= steps; i++) {
4071
+ const sx = agent.position[0] + (x - agent.position[0]) * i / steps;
4072
+ const sz = agent.position[2] + (z - agent.position[2]) * i / steps;
4073
+ const habitat = world.habitat(sx, sz, species.margin);
4074
+ const choice = world.choices(sx, sz).find((entry) => entry.species.id === species.id);
4075
+ if (!suitable(species, habitat) || choice === void 0 || !choice.habitats.includes(habitat.kind)) {
4076
+ destination = void 0;
4077
+ break;
4078
+ }
4079
+ destination = habitat;
4080
+ }
4081
+ if (destination !== void 0) {
4082
+ agent.position = [
4083
+ x,
4084
+ q4(heightFor(species, destination)),
4085
+ z
4086
+ ];
4087
+ agent.heading = dmath.atan2(dx, dz);
4088
+ agent.speed = q4(travel * 20);
4089
+ agent.phase = q4((agent.phase + travel / Math.max(.1, species.body.length)) % 1);
4090
+ } else agent.nextDecision = tick + 1;
4091
+ } else if (species.motion === "fly" || species.motion === "swim") agent.nextDecision = tick + 1;
4092
+ next.push(agent);
4093
+ }
4094
+ return next;
4095
+ }
4096
+ //#endregion
4097
+ //#region src/kernel/wildlife-types.ts
4098
+ /** Data-only animal silhouettes and habitat populations. Content owns species and range facts. */
4099
+ const WILDLIFE_FAMILIES = [
4100
+ "ungulate",
4101
+ "canid",
4102
+ "feline",
4103
+ "rodent",
4104
+ "lagomorph",
4105
+ "hopper",
4106
+ "elephant",
4107
+ "bird",
4108
+ "reptile",
4109
+ "fish",
4110
+ "insect"
4111
+ ];
4112
+ const id = z.string().regex(/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/);
4113
+ const color = z.string().regex(/^#[0-9a-fA-F]{6}$/);
4114
+ const wildlifeSpeciesSchema = z.strictObject({
4115
+ id,
4116
+ version: z.int().positive(),
4117
+ title: z.string().min(1),
4118
+ taxon: z.string().min(1).optional(),
4119
+ range: z.string().min(1).optional(),
4120
+ winterColor: color.optional(),
4121
+ inactiveInWinter: z.boolean().optional(),
4122
+ body: z.strictObject({
4123
+ family: z.enum(WILDLIFE_FAMILIES),
4124
+ height: z.number().min(.01).max(7),
4125
+ length: z.number().min(.01).max(12),
4126
+ width: z.number().min(.005).max(5),
4127
+ color,
4128
+ accent: color,
4129
+ details: z.array(z.enum([
4130
+ "antlers",
4131
+ "horns",
4132
+ "long-neck",
4133
+ "bushy-tail",
4134
+ "stripes",
4135
+ "spots",
4136
+ "wader",
4137
+ "waterfowl",
4138
+ "raptor",
4139
+ "parrot",
4140
+ "long-tail"
4141
+ ]))
4142
+ }),
4143
+ motion: z.enum([
4144
+ "walk",
4145
+ "hop",
4146
+ "fly",
4147
+ "swim",
4148
+ "crawl"
4149
+ ]),
4150
+ speed: z.number().min(.01).max(30),
4151
+ roam: z.number().min(1).max(200),
4152
+ clearance: z.number().min(0).max(80),
4153
+ rest: z.number().min(0).max(1),
4154
+ margin: z.number().min(.02).max(8)
4155
+ }).refine((species) => species.taxon === void 0 === (species.range === void 0), { message: "Named wildlife taxa require an attributed range; unnamed functional groups omit both." });
4156
+ //#endregion
3802
4157
  //#region src/kernel.ts
3803
4158
  registerAmbientSchema();
3804
4159
  //#endregion
3805
- export { AMBIENT_AGENT_COMPONENT, AMBIENT_ENTITY, AMBIENT_KINDS, AMBIENT_OBSERVER_COMPONENT, AMBIENT_ROLE_COMPONENT, AMBIENT_STATE_COMPONENT, AmbientAgent, AmbientObserver, AmbientRole, AmbientState, CAR_COLORS, DEFAULT_POLICY, DEFAULT_TEMPLATES, DEFAULT_TYPES, GRID_CELL, KIND_SPEED, LaneGrid, TRANSPORT_NETWORK_EXAMPLE, TRANSPORT_NETWORK_FORMAT, TransportNetwork, agentRotation, agentSample, allRed, ambientCapability, ambientOf, ambientScriptApi, chooseNext, classifyFeature, clipPolyline, edgeHeight, featureDrafts, fmix32, idmAcceleration, installAmbient, laneCoordinate, laneEdgeDistance, laneSample, mergePolicy, networkToDocument, pickWeighted, planarSplit, policyForBudget, pseudoAngle, registerAmbientSchema, sampleConnector, sampleLaneBody, signalColor, signalTiming, stepAgents, stoppingDistance, unit01, walkBack };
4160
+ export { AMBIENT_AGENT_COMPONENT, AMBIENT_ENTITY, AMBIENT_KINDS, AMBIENT_OBSERVER_COMPONENT, AMBIENT_ROLE_COMPONENT, AMBIENT_STATE_COMPONENT, AmbientAgent, AmbientObserver, AmbientRole, AmbientState, CAR_COLORS, DEFAULT_POLICY, DEFAULT_TEMPLATES, DEFAULT_TYPES, GRID_CELL, KIND_SPEED, LaneGrid, TRANSPORT_NETWORK_EXAMPLE, TRANSPORT_NETWORK_FORMAT, TransportNetwork, WILDLIFE_CELL_METERS, WILDLIFE_FAMILIES, WILDLIFE_TICK_RATE, agentRotation, agentSample, allRed, ambientCapability, ambientOf, ambientScriptApi, chooseNext, classifyFeature, clipPolyline, edgeHeight, featureDrafts, fmix32, idmAcceleration, installAmbient, laneCoordinate, laneEdgeDistance, laneSample, mergePolicy, networkToDocument, pickWeighted, planarSplit, policyForBudget, pseudoAngle, registerAmbientSchema, sampleConnector, sampleLaneBody, signalColor, signalTiming, stepAgents, stepWildlife, stoppingDistance, unit01, walkBack, wildlifeCandidates, wildlifeSpeciesSchema };