@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,673 @@
1
+ import { dmath } from "@bendyline/molen-kernel/determinism";
2
+ import { defineComponent } from "@bendyline/molen-kernel/world";
3
+ import { getSchema, registerComponent, registerRenderableKind, registerSchema } from "@bendyline/molen-schema";
4
+ import { z } from "zod";
5
+ import { groupTransportationFeatures, inferLaneCount, isTransportLink, joinTerrainLines, roadWidth, transportKind, transportWidth } from "@bendyline/molen-terrain/kernel";
6
+ //#region src/kernel/graph/drafts.ts
7
+ /**
8
+ * Map features → edge drafts: world-metre polylines with a transport class, kind, width, lane
9
+ * count and grade, clipped to their tile so neighbouring tiles never duplicate a road. Widths,
10
+ * lane counts and surface lifts come from the terrain painter's rules, so simulated lanes sit on
11
+ * painted lanes.
12
+ */
13
+ /** Design speeds in m/s by kind. */
14
+ const KIND_SPEED = {
15
+ motorway: 27,
16
+ trunk: 22,
17
+ primary: 17,
18
+ secondary: 15,
19
+ tertiary: 13,
20
+ street: 11,
21
+ living: 5,
22
+ service: 5.5,
23
+ path: 1.4,
24
+ crossing: 1.4,
25
+ rail: 20,
26
+ tram: 12
27
+ };
28
+ /** Classify a mapped feature; `undefined` for features no agent uses. */
29
+ function classifyFeature(feature) {
30
+ const cls = feature.class.toLowerCase();
31
+ const sub = (feature.subclass ?? "").toLowerCase();
32
+ 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;
34
+ const kind = transportKind(feature);
35
+ if (kind === "rail") {
36
+ if (/disused|abandoned|construction|proposed|platform|station|miniature|funicular/.test(sub)) return void 0;
37
+ if (feature.service !== void 0 && /yard|siding|spur|crossover/.test(feature.service)) return void 0;
38
+ return {
39
+ class: "rail",
40
+ kind: /tram/.test(sub) ? "tram" : "rail"
41
+ };
42
+ }
43
+ if (kind === "path") {
44
+ if (/cycleway|bridleway/.test(sub)) return void 0;
45
+ return {
46
+ class: "walk",
47
+ kind: "path"
48
+ };
49
+ }
50
+ if (sub === "crossing") return {
51
+ class: "walk",
52
+ kind: "crossing"
53
+ };
54
+ if (sub === "sidewalk" || sub === "footway") return {
55
+ class: "walk",
56
+ kind: "path"
57
+ };
58
+ if (kind === "motorway") return {
59
+ class: "road",
60
+ kind: "motorway"
61
+ };
62
+ if (kind === "service") return {
63
+ class: "road",
64
+ kind: "service"
65
+ };
66
+ const bare = sub.replace(/_link$/, "");
67
+ if (bare === "trunk") return {
68
+ class: "road",
69
+ kind: "trunk"
70
+ };
71
+ if (bare === "primary") return {
72
+ class: "road",
73
+ kind: "primary"
74
+ };
75
+ if (bare === "secondary") return {
76
+ class: "road",
77
+ kind: "secondary"
78
+ };
79
+ if (bare === "tertiary") return {
80
+ class: "road",
81
+ kind: "tertiary"
82
+ };
83
+ if (/living|pedestrian/.test(bare)) return {
84
+ class: "road",
85
+ kind: "living"
86
+ };
87
+ if (/track|construction|proposed|raceway/.test(bare)) return void 0;
88
+ return {
89
+ class: "road",
90
+ kind: "street"
91
+ };
92
+ }
93
+ /**
94
+ * Clip a polyline to an axis-aligned rectangle, returning the visible pieces (a line that leaves
95
+ * and re-enters the tile yields several pieces).
96
+ */
97
+ function clipPolyline(points, minX, minZ, maxX, maxZ) {
98
+ const pieces = [];
99
+ let current;
100
+ for (let i = 1; i < points.length; i++) {
101
+ const a = points[i - 1];
102
+ const b = points[i];
103
+ const clipped = clipSegment(a, b, minX, minZ, maxX, maxZ);
104
+ if (clipped === void 0) {
105
+ current = void 0;
106
+ continue;
107
+ }
108
+ const [p, q, enteredInside, leftInside] = clipped;
109
+ if (current === void 0 || !enteredInside) {
110
+ current = [p];
111
+ pieces.push(current);
112
+ }
113
+ const last = current[current.length - 1];
114
+ if (last[0] !== p[0] || last[1] !== p[1]) current.push(p);
115
+ current.push(q);
116
+ if (!leftInside) current = void 0;
117
+ }
118
+ return pieces.filter((piece) => piece.length >= 2);
119
+ }
120
+ /** Liang–Barsky: the visible part of a segment and whether it starts/ends at the original points. */
121
+ function clipSegment(a, b, minX, minZ, maxX, maxZ) {
122
+ const dx = b[0] - a[0];
123
+ const dz = b[1] - a[1];
124
+ let t0 = 0;
125
+ let t1 = 1;
126
+ const edges = [
127
+ [-dx, a[0] - minX],
128
+ [dx, maxX - a[0]],
129
+ [-dz, a[1] - minZ],
130
+ [dz, maxZ - a[1]]
131
+ ];
132
+ for (const [p, q] of edges) {
133
+ if (p === 0) {
134
+ if (q < 0) return void 0;
135
+ continue;
136
+ }
137
+ const r = q / p;
138
+ if (p < 0) {
139
+ if (r > t1) return void 0;
140
+ if (r > t0) t0 = r;
141
+ } else {
142
+ if (r < t0) return void 0;
143
+ if (r < t1) t1 = r;
144
+ }
145
+ }
146
+ if (t1 - t0 <= 0 && !(t0 === 0 && t1 === 0 && dx === 0 && dz === 0)) return void 0;
147
+ const p = t0 === 0 ? [a[0], a[1]] : [a[0] + dx * t0, a[1] + dz * t0];
148
+ const q = t1 === 1 ? [b[0], b[1]] : [a[0] + dx * t1, a[1] + dz * t1];
149
+ if (t0 > 0) snapToBoundary(p, minX, minZ, maxX, maxZ);
150
+ if (t1 < 1) snapToBoundary(q, minX, minZ, maxX, maxZ);
151
+ return [
152
+ p,
153
+ q,
154
+ t0 === 0,
155
+ t1 === 1
156
+ ];
157
+ }
158
+ function snapToBoundary(p, minX, minZ, maxX, maxZ) {
159
+ const eps = 1e-6;
160
+ if (dmath.abs(p[0] - minX) < eps) p[0] = minX;
161
+ else if (dmath.abs(p[0] - maxX) < eps) p[0] = maxX;
162
+ if (dmath.abs(p[1] - minZ) < eps) p[1] = minZ;
163
+ else if (dmath.abs(p[1] - maxZ) < eps) p[1] = maxZ;
164
+ }
165
+ /** Road lanes per direction for a feature, clamped so no lane is narrower than 2.5 m. */
166
+ function roadLanes(feature, width) {
167
+ let total = inferLaneCount(feature, width);
168
+ const minimum = feature.oneway === true ? 1 : 2;
169
+ if (width / total < 2.5) total = dmath.max(minimum, dmath.floor(width / 2.5));
170
+ if (feature.oneway === true && feature.lanes === void 0) total = dmath.max(1, dmath.min(total, dmath.round(width / 3.3)));
171
+ return { total: dmath.max(minimum, total) };
172
+ }
173
+ /** Convert a tile's transportation features to clipped world-metre drafts. */
174
+ function featureDrafts(input, options) {
175
+ const { origin, tileSize } = input;
176
+ const minX = origin[0];
177
+ const minZ = origin[1];
178
+ const maxX = origin[0] + tileSize;
179
+ const maxZ = origin[1] + tileSize;
180
+ const drafts = [];
181
+ const runways = [];
182
+ const toWorld = (line) => line.map((p) => [origin[0] + p[0] * tileSize, origin[1] + p[1] * tileSize]);
183
+ for (const feature of groupTransportationFeatures(input.features)) {
184
+ const classified = classifyFeature(feature);
185
+ if (classified === void 0) continue;
186
+ if (classified === "runway") {
187
+ for (const line of feature.lines) {
188
+ const world = toWorld(line);
189
+ if (world.length >= 2) runways.push({
190
+ a: world[0],
191
+ b: world[world.length - 1]
192
+ });
193
+ }
194
+ continue;
195
+ }
196
+ if (feature.tunnel === true && options.tunnels === "skip") continue;
197
+ 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);
199
+ const lanes = classified.class === "road" ? roadLanes(feature, width).total : 2;
200
+ const link = isTransportLink(feature);
201
+ for (const line of joinTerrainLines(feature.lines)) for (const piece of clipPolyline(toWorld(line), minX, minZ, maxX, maxZ)) {
202
+ const draft = {
203
+ class: classified.class,
204
+ kind: classified.kind,
205
+ points: piece,
206
+ width,
207
+ lanes,
208
+ oneway: feature.oneway === true && classified.class === "road",
209
+ layer: feature.layer ?? 0,
210
+ bridge: feature.bridge === true,
211
+ tunnel: feature.tunnel === true,
212
+ link,
213
+ ...feature.name !== void 0 ? { name: feature.name } : {},
214
+ ...feature.deckElevation !== void 0 ? { deckElevation: feature.deckElevation } : {}
215
+ };
216
+ if (feature.bridgeConnections !== void 0 && feature.bridgeConnections.length > 0) draft.bridgeConnections = feature.bridgeConnections.map((c) => ({
217
+ point: [origin[0] + c.point[0] * tileSize, origin[1] + c.point[1] * tileSize],
218
+ elevation: c.elevation,
219
+ radius: c.radius
220
+ }));
221
+ drafts.push(draft);
222
+ }
223
+ }
224
+ return {
225
+ drafts,
226
+ runways
227
+ };
228
+ }
229
+ const POI_KINDS = new Set([
230
+ "station",
231
+ "tram_stop",
232
+ "bus_stop",
233
+ "traffic_signals",
234
+ "crossing",
235
+ "aerodrome"
236
+ ]);
237
+ /** Convert a tile's POIs to world points (only those inside the tile). */
238
+ function tilePois(pois, origin, tileSize) {
239
+ const result = [];
240
+ for (const poi of pois ?? []) {
241
+ const kind = (poi.subclass ?? poi.class).toLowerCase();
242
+ const matched = POI_KINDS.has(kind) ? kind : POI_KINDS.has(poi.class) ? poi.class : void 0;
243
+ if (matched === void 0) continue;
244
+ const [u, v] = poi.point;
245
+ if (u < 0 || u > 1 || v < 0 || v > 1) continue;
246
+ result.push({
247
+ kind: matched,
248
+ x: origin[0] + u * tileSize,
249
+ z: origin[1] + v * tileSize,
250
+ ...poi.name !== void 0 ? { name: poi.name } : {}
251
+ });
252
+ }
253
+ return result;
254
+ }
255
+ //#endregion
256
+ //#region src/kernel/graph/doc.ts
257
+ /**
258
+ * molen/transport-network@1 documents: hand-authored or baked networks for scenes without
259
+ * streamed map tiles. A document is a list of ways (polylines with a class and tags); ways that
260
+ * share a vertex, cross at the same grade or end on one another connect automatically.
261
+ */
262
+ const TRANSPORT_NETWORK_FORMAT = "molen/transport-network@1";
263
+ const ROAD_KINDS = new Set([
264
+ "motorway",
265
+ "trunk",
266
+ "primary",
267
+ "secondary",
268
+ "tertiary",
269
+ "street",
270
+ "living",
271
+ "service"
272
+ ]);
273
+ function roadKindOf(subclass) {
274
+ const bare = (subclass ?? "").replace(/_link$/, "");
275
+ if (ROAD_KINDS.has(bare)) return bare;
276
+ if (bare === "living_street") return "living";
277
+ return "street";
278
+ }
279
+ /** One way → one draft (air ways are skipped: aircraft fly corridors, not lanes). */
280
+ function wayDraft(way) {
281
+ if (way.class === "air" || way.points.length < 2) return void 0;
282
+ const points = way.points.map((p) => p.length === 3 ? [p[0], p[2]] : [p[0], p[1]]);
283
+ const heights = way.points.every((p) => p.length === 3) ? way.points.map((p) => p[1]) : void 0;
284
+ const common = {
285
+ points,
286
+ ...heights !== void 0 ? { heights } : {},
287
+ layer: way.layer ?? 0,
288
+ bridge: way.bridge === true,
289
+ tunnel: way.tunnel === true,
290
+ link: /_link$/.test(way.subclass ?? ""),
291
+ ...way.speed !== void 0 ? { speed: way.speed } : {},
292
+ ...way.name !== void 0 ? { name: way.name } : {}
293
+ };
294
+ if (way.class === "rail") return {
295
+ ...common,
296
+ class: "rail",
297
+ kind: way.subclass === "tram" ? "tram" : "rail",
298
+ width: way.width ?? 3,
299
+ lanes: 2,
300
+ oneway: false
301
+ };
302
+ if (way.class === "path") return {
303
+ ...common,
304
+ class: "walk",
305
+ kind: way.subclass === "crossing" ? "crossing" : "path",
306
+ width: way.width ?? 2.4,
307
+ lanes: 2,
308
+ oneway: false
309
+ };
310
+ const kind = roadKindOf(way.subclass);
311
+ const width = dmath.min(80, way.width ?? roadWidth(way.subclass ?? "residential"));
312
+ const lanes = roadLanes({
313
+ ...way.lanes !== void 0 ? { lanes: way.lanes } : {},
314
+ oneway: way.oneway === true
315
+ }, width).total;
316
+ return {
317
+ ...common,
318
+ class: "road",
319
+ kind,
320
+ width,
321
+ lanes,
322
+ oneway: way.oneway === true
323
+ };
324
+ }
325
+ /** Stations and signals as points of interest. */
326
+ function documentPois(doc) {
327
+ const pois = [];
328
+ for (const station of doc.stations ?? []) pois.push({
329
+ kind: station.kind === "rail" ? "station" : "bus_stop",
330
+ x: station.at[0],
331
+ z: station.at[1],
332
+ name: station.id,
333
+ ...station.dwell !== void 0 ? { dwell: station.dwell } : {}
334
+ });
335
+ for (const signal of doc.signals ?? []) pois.push({
336
+ kind: signal.kind === "light" ? "traffic_signals" : "give_way",
337
+ x: signal.at[0],
338
+ z: signal.at[1]
339
+ });
340
+ for (const aerodrome of doc.aerodromes ?? []) pois.push({
341
+ kind: "aerodrome",
342
+ x: aerodrome.at[0],
343
+ z: aerodrome.at[1],
344
+ name: aerodrome.id
345
+ });
346
+ return pois;
347
+ }
348
+ /** Aerodrome runways as segments. */
349
+ function documentRunways(doc) {
350
+ return (doc.aerodromes ?? []).map((aerodrome) => {
351
+ const heading = aerodrome.heading ?? 0;
352
+ const half = (aerodrome.length ?? 2500) / 2;
353
+ const dx = dmath.sin(heading) * half;
354
+ const dz = dmath.cos(heading) * half;
355
+ return {
356
+ a: [aerodrome.at[0] - dx, aerodrome.at[1] - dz],
357
+ b: [aerodrome.at[0] + dx, aerodrome.at[1] + dz]
358
+ };
359
+ });
360
+ }
361
+ const TRANSPORT_NETWORK_EXAMPLE = {
362
+ format: TRANSPORT_NETWORK_FORMAT,
363
+ name: "crossroads",
364
+ drivingSide: "right",
365
+ ways: [
366
+ {
367
+ id: "main",
368
+ class: "road",
369
+ subclass: "primary",
370
+ points: [[-200, 0], [200, 0]],
371
+ lanes: 4
372
+ },
373
+ {
374
+ id: "cross",
375
+ class: "road",
376
+ subclass: "residential",
377
+ points: [[0, -200], [0, 200]]
378
+ },
379
+ {
380
+ id: "tram",
381
+ class: "rail",
382
+ subclass: "tram",
383
+ points: [[-200, 30], [200, 30]]
384
+ }
385
+ ],
386
+ stations: [{
387
+ id: "central",
388
+ at: [0, 30],
389
+ kind: "rail"
390
+ }],
391
+ signals: [{
392
+ at: [0, 0],
393
+ kind: "light"
394
+ }]
395
+ };
396
+ //#endregion
397
+ //#region src/kernel/schema.ts
398
+ /**
399
+ * The ambient vocabulary: components, the `ambient-vehicle` renderable kind and the
400
+ * molen/transport-network@1 format. Kernel-free (schema + zod only) so both halves register it on
401
+ * import: a page validates scenes with the client half alone, tooling and Workers with the kernel
402
+ * half.
403
+ */
404
+ const AMBIENT_AGENT_COMPONENT = "ambientAgent";
405
+ const AMBIENT_OBSERVER_COMPONENT = "ambientObserver";
406
+ const AMBIENT_ROLE_COMPONENT = "ambientRole";
407
+ const AMBIENT_STATE_COMPONENT = "ambientState";
408
+ const num = z.number();
409
+ const vec2 = z.array(num).length(2);
410
+ const vec3 = z.array(num).length(3);
411
+ const kind = z.enum([
412
+ "car",
413
+ "pedestrian",
414
+ "train",
415
+ "aircraft"
416
+ ]);
417
+ const ambientAgentSchema = z.strictObject({
418
+ kind: kind.describe("Agent class."),
419
+ type: z.string().describe("Content type id (e.g. molen.entities.vehicle.sedan), figure preset, or \"proxy\"."),
420
+ color: z.string().describe("Body colour (#rrggbb).").optional(),
421
+ lane: z.string().describe("Lane id the agent is on (\"\" for aircraft)."),
422
+ s: num.describe("Metres along the lane; negative while on the connector into it."),
423
+ speed: num.nonnegative().describe("Speed along the lane in m/s."),
424
+ prev: z.string().describe("Previous lane (its connector leads onto `lane`).").optional(),
425
+ next: z.string().describe("Chosen next lane.").optional(),
426
+ seed: z.int().nonnegative().describe("Per-agent seed for every random choice it makes."),
427
+ length: num.positive().describe("Body length in metres."),
428
+ width: num.positive().describe("Body width in metres."),
429
+ state: z.enum([
430
+ "move",
431
+ "wait",
432
+ "dwell",
433
+ "idle"
434
+ ]).describe("Moving, waiting (queue, signal, crossing), dwelling at a stop, or idling."),
435
+ since: z.int().nonnegative().describe("Tick the current state began."),
436
+ hops: z.int().nonnegative().describe("Lane transitions so far (routing draw stream)."),
437
+ hidden: z.boolean().describe("Inside a tunnel: simulated but not drawn.").optional(),
438
+ consist: z.string().describe("Train cars: the lead agent of the consist.").optional(),
439
+ carIndex: z.int().positive().describe("Train cars: position behind the lead (1 = first).").optional(),
440
+ trail: z.array(z.string()).describe("Train leads: the lanes behind the lead, most recent first.").optional(),
441
+ served: z.string().describe("The last stop served (not stopped at again).").optional(),
442
+ air: z.strictObject({
443
+ x: num.describe("Corridor start X."),
444
+ z: num.describe("Corridor start Z."),
445
+ dx: num.describe("Unit heading X."),
446
+ dz: num.describe("Unit heading Z."),
447
+ y0: num.describe("Altitude at the start."),
448
+ y1: num.describe("Altitude at the end."),
449
+ length: num.positive().describe("Corridor length in metres.")
450
+ }).describe("Aircraft: the straight corridor flown (s runs along it).").optional(),
451
+ spawnedTick: z.int().nonnegative().describe("Tick the agent appeared (clients fade it in).")
452
+ });
453
+ const ambientObserverSchema = z.strictObject({
454
+ radius: num.positive().describe("Override the car spawn radius in metres.").optional(),
455
+ despawnRadius: num.positive().describe("Override the car despawn radius in metres.").optional(),
456
+ density: num.nonnegative().describe("Scale every class density (1 = default).").optional()
457
+ });
458
+ const ambientRoleSchema = z.strictObject({
459
+ role: z.enum([
460
+ "car",
461
+ "bus",
462
+ "rail",
463
+ "aircraft"
464
+ ]).describe("Which ambient pool the type joins (buses drive with cars)."),
465
+ length: num.positive().describe("Body length in metres (default from vehicle.spec).").optional(),
466
+ width: num.positive().describe("Body width in metres (default from vehicle.spec).").optional(),
467
+ height: num.positive().describe("Body height in metres (default from vehicle.spec).").optional(),
468
+ cruise: num.positive().describe("Preferred cruise speed in m/s.").optional(),
469
+ max: num.positive().describe("Top speed in m/s.").optional(),
470
+ weight: num.nonnegative().describe("Relative spawn weight within its pool (default 1).").optional(),
471
+ cars: z.int().positive().describe("Rail: cars per consist (default 2).").optional(),
472
+ colors: z.array(z.string()).min(1).describe("Paint colours spawned agents pick from (#rrggbb).").optional(),
473
+ visual: z.strictObject({
474
+ wheelNodes: z.array(z.string()).describe("Wheel nodes (their first child spins).").optional(),
475
+ frontWheelNodes: z.array(z.string()).describe("Wheel nodes that steer.").optional(),
476
+ paintMaterial: z.string().describe("Material name tinted with the agent colour.").optional(),
477
+ wheelRadius: num.positive().describe("Wheel radius in metres.").optional(),
478
+ wheelbase: num.positive().describe("Axle spacing in metres.").optional(),
479
+ rotors: z.array(z.string()).describe("Aircraft: nodes spun about Z (fans, propellers).").optional(),
480
+ gearNodes: z.array(z.string()).describe("Aircraft: landing gear shown on approach.").optional()
481
+ }).describe("How the model animates when drawn in full near the camera (types without a vehicle component).").optional()
482
+ });
483
+ const observerFields = z.strictObject({
484
+ pos: vec3.describe("Observer position.").optional(),
485
+ forward: vec2.describe("Unit view direction [x, z]; spawns avoid the view cone near it.").optional(),
486
+ entity: z.string().describe("Entity whose transform is the observer.").optional(),
487
+ setAtTick: z.int().nonnegative().describe("Tick the observer was last set.")
488
+ });
489
+ const ambientStateSchema = z.strictObject({
490
+ observer: observerFields.describe("Where agents spawn around.").optional(),
491
+ nextSeq: z.int().nonnegative().describe("Sequence number of the next spawned agent."),
492
+ spawned: z.int().nonnegative().describe("Agents spawned so far."),
493
+ despawned: z.int().nonnegative().describe("Agents removed so far."),
494
+ policy: z.record(z.string(), z.json()).describe("Policy overrides set by the ambient.policy command.").optional()
495
+ });
496
+ const point = z.union([vec2, vec3]);
497
+ const waySchema = z.strictObject({
498
+ id: z.string().min(1).describe("Optional stable id.").optional(),
499
+ class: z.enum([
500
+ "road",
501
+ "rail",
502
+ "path",
503
+ "air"
504
+ ]).describe("What moves on it."),
505
+ subclass: z.string().describe("motorway, trunk, primary, secondary, tertiary, residential, service; rail/tram; crossing.").optional(),
506
+ points: z.array(point).min(2).describe("[x, z] or [x, y, z] points in scene metres (y = road surface height)."),
507
+ oneway: z.boolean().describe("Traffic only in point order.").optional(),
508
+ lanes: z.int().positive().describe("Total lanes across both directions.").optional(),
509
+ width: num.positive().describe("Carriageway width in metres.").optional(),
510
+ layer: z.int().describe("Grade: different layers never connect mid-way.").optional(),
511
+ speed: num.positive().describe("Design speed in m/s.").optional(),
512
+ bridge: z.boolean().optional(),
513
+ tunnel: z.boolean().optional(),
514
+ name: z.string().optional()
515
+ });
516
+ const transportNetworkSchema = z.strictObject({
517
+ format: z.literal(TRANSPORT_NETWORK_FORMAT).describe("Format envelope; always 'molen/transport-network@1'."),
518
+ name: z.string().optional(),
519
+ origin: z.union([z.strictObject({
520
+ latitude: num,
521
+ longitude: num
522
+ }), z.strictObject({
523
+ x: num,
524
+ z: num
525
+ })]).describe("Where the network came from (geographic anchor of a baked network).").optional(),
526
+ drivingSide: z.enum(["right", "left"]).describe("Traffic side (default 'right').").optional(),
527
+ sidewalks: z.boolean().describe("Infer sidewalks along streets that have no mapped paths nearby (default false).").optional(),
528
+ ways: z.array(waySchema).describe("Roads, railways and paths."),
529
+ stations: z.array(z.strictObject({
530
+ id: z.string().min(1),
531
+ at: vec2.describe("[x, z]; projected onto the nearest rail (rail) or footway (bus)."),
532
+ kind: z.enum(["rail", "bus"]),
533
+ dwell: num.positive().describe("Dwell time in seconds.").optional()
534
+ })).describe("Stops trains (and buses) serve.").optional(),
535
+ signals: z.array(z.strictObject({
536
+ at: vec2,
537
+ kind: z.enum([
538
+ "stop",
539
+ "yield",
540
+ "light"
541
+ ])
542
+ })).describe("Junction controls: a light signalises the junction nearest the point; a stop or yield sign makes the junction arm nearest the point give way.").optional(),
543
+ aerodromes: z.array(z.strictObject({
544
+ id: z.string().min(1),
545
+ at: vec2,
546
+ heading: num.describe("Runway heading in radians about +Y (0 = +Z).").optional(),
547
+ length: num.positive().describe("Runway length in metres (default 2500).").optional()
548
+ })).describe("Runways aircraft approach and depart.").optional()
549
+ });
550
+ function validateNetwork(data) {
551
+ const doc = data;
552
+ const issues = [];
553
+ const ids = /* @__PURE__ */ new Set();
554
+ doc.ways.forEach((way, i) => {
555
+ if (way.id !== void 0) {
556
+ if (ids.has(way.id)) issues.push({
557
+ path: `/ways/${i}/id`,
558
+ code: "duplicate_id",
559
+ message: `duplicate way id "${way.id}"`,
560
+ docsRef: "guide/ambient-life.md"
561
+ });
562
+ ids.add(way.id);
563
+ }
564
+ way.points.forEach((p, j) => {
565
+ if (!p.every(Number.isFinite)) issues.push({
566
+ path: `/ways/${i}/points/${j}`,
567
+ code: "not_finite",
568
+ message: "way points must be finite numbers",
569
+ docsRef: "guide/ambient-life.md"
570
+ });
571
+ });
572
+ });
573
+ return issues;
574
+ }
575
+ const AMBIENT_AGENT_EXAMPLE = {
576
+ kind: "car",
577
+ type: "molen.entities.vehicle.sedan",
578
+ color: "#4d76b8",
579
+ lane: "15/5245/11443#k3j9x2>f0",
580
+ s: 42.5,
581
+ speed: 11.2,
582
+ seed: 1964432,
583
+ length: 4.65,
584
+ width: 1.82,
585
+ state: "move",
586
+ since: 1200,
587
+ hops: 3,
588
+ spawnedTick: 1180
589
+ };
590
+ let registered = false;
591
+ /** Register the ambient components, renderable kind and format (idempotent). */
592
+ function registerAmbientSchema() {
593
+ if (registered) return;
594
+ registered = true;
595
+ const owner = "ambient";
596
+ const docsRef = "guide/ambient-life.md";
597
+ 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.",
599
+ owner,
600
+ examples: [AMBIENT_AGENT_EXAMPLE],
601
+ docsRef
602
+ }, { override: true });
603
+ registerComponent(AMBIENT_OBSERVER_COMPONENT, ambientObserverSchema, {
604
+ description: "Marks the entity ambient NPCs spawn around (usually the player or camera rig), with optional radius and density overrides.",
605
+ owner,
606
+ examples: [{}, {
607
+ radius: 200,
608
+ density: .5
609
+ }],
610
+ docsRef
611
+ }, { override: true });
612
+ 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.",
614
+ owner,
615
+ examples: [{
616
+ role: "car",
617
+ cruise: 13,
618
+ max: 25
619
+ }, {
620
+ role: "rail",
621
+ length: 27,
622
+ cars: 2
623
+ }],
624
+ docsRef
625
+ }, { override: true });
626
+ registerComponent(AMBIENT_STATE_COMPONENT, ambientStateSchema, {
627
+ description: "Kernel-owned ambient bookkeeping on the `$ambient` entity: observer, spawn sequence and policy overrides.",
628
+ owner,
629
+ examples: [{
630
+ nextSeq: 12,
631
+ spawned: 12,
632
+ despawned: 3,
633
+ observer: {
634
+ pos: [
635
+ 0,
636
+ 0,
637
+ 0
638
+ ],
639
+ setAtTick: 0
640
+ }
641
+ }],
642
+ docsRef
643
+ }, { override: true });
644
+ registerRenderableKind("ambient-vehicle", {
645
+ description: "an ambient NPC vehicle: an instanced proxy from its `ambientAgent` dimensions, or the content model named by `ref` near the camera",
646
+ owner
647
+ });
648
+ if (getSchema("transport-network") === void 0) registerSchema("transport-network", transportNetworkSchema, {
649
+ id: TRANSPORT_NETWORK_FORMAT,
650
+ title: "Transport network",
651
+ description: "Roads, railways and paths ambient NPCs move on, for scenes without streamed map tiles. Ways that share a vertex, cross at the same grade or end on one another connect.",
652
+ examples: [TRANSPORT_NETWORK_EXAMPLE],
653
+ docsRef,
654
+ validate: validateNetwork
655
+ });
656
+ }
657
+ //#endregion
658
+ //#region src/kernel/components.ts
659
+ /** Typed component handles and data shapes for the ambient capability. */
660
+ const AMBIENT_KINDS = [
661
+ "car",
662
+ "pedestrian",
663
+ "train",
664
+ "aircraft"
665
+ ];
666
+ const AmbientAgent = defineComponent(AMBIENT_AGENT_COMPONENT);
667
+ const AmbientObserver = defineComponent(AMBIENT_OBSERVER_COMPONENT);
668
+ const AmbientRole = defineComponent(AMBIENT_ROLE_COMPONENT);
669
+ const AmbientState = defineComponent(AMBIENT_STATE_COMPONENT);
670
+ /** The singleton entity holding ambient bookkeeping. */
671
+ const AMBIENT_ENTITY = "$ambient";
672
+ //#endregion
673
+ export { KIND_SPEED as _, AmbientRole as a, featureDrafts as b, AMBIENT_OBSERVER_COMPONENT as c, registerAmbientSchema as d, TRANSPORT_NETWORK_EXAMPLE as f, wayDraft as g, documentRunways as h, AmbientObserver as i, AMBIENT_ROLE_COMPONENT as l, documentPois as m, AMBIENT_KINDS as n, AmbientState as o, TRANSPORT_NETWORK_FORMAT as p, AmbientAgent as r, AMBIENT_AGENT_COMPONENT as s, AMBIENT_ENTITY as t, AMBIENT_STATE_COMPONENT as u, classifyFeature as v, tilePois as x, clipPolyline as y };