#!/usr/bin/env node "use strict"; const assert = require("node:assert/strict"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const source = fs.readFileSync(path.join(__dirname, "lib/cesium-preview.js"), "utf8"); function functionSource(name) { const start = source.indexOf(" function " + name + "("); assert.ok(start >= 0, name); const end = source.indexOf("\n function ", start + 1); return source.slice(start, end < 0 ? source.length : end); } let seconds = 0; class Time { constructor(value = 0) { this.value = value; } clone() { return new Time(this.value); } } const context = vm.createContext({ performance: { now: () => seconds * 1000 }, toggleVehicles: { checked: true }, Cesium: { JulianDate: { secondsDifference: (a, b) => a.value - b.value, clone: (a, b) => { b.value = a.value; return b; }, }, CallbackProperty: class { constructor(callback) { this.callback = callback; } }, }, distanceMeters: (a, b) => Math.hypot((a[0] - b[0]) * 100000, (a[1] - b[1]) * 100000), }); vm.runInContext(["participantRoute", "createParticipantSimulation", "signalPhaseAtElapsed"].map(functionSource).join("\n"), context); const plan = { cycleSeconds: 60, initialAllRedSeconds: 5, groups: { 0: [{ from: 0, to: 25, state: "green" }, { from: 25, to: 28, state: "yellow" }, { from: 28, to: 60, state: "red" }], 1: [{ from: 0, to: 32, state: "red" }, { from: 32, to: 57, state: "green" }, { from: 57, to: 60, state: "yellow" }], } }; const templates = [ { id: "cars", kind: "vehicle", fleet: 1, approachLaneId: "lane", speedMetersPerSecond: 8, vehicleLengthMeters: 4.6, coordinates: [[0, 0], [0.0002, 0], [0.0008, 0]], stops: [{ distance: 20, phaseGroup: 0 }], crossingConflicts: [] }, { id: "walk", kind: "pedestrian", fleet: 1, crossingId: "zebra", phaseGroup: 0, speedMetersPerSecond: 2, coordinates: [[0, 0.001], [0.0003, 0.001]], stops: [] }, ]; let tick; const simulation = context.createParticipantSimulation({ clock: { onTick: { addEventListener: (fn) => { tick = fn; } } } }, templates, new Time(), 8, {}, plan, 0); let releases = 0; let completedCrossings = 0; for (let frame = 1; frame <= 12000; frame += 1) { seconds = frame * 0.05; const previous = simulation.agents.map((agent) => ({ ...agent.state })); tick({ currentTime: new Time(seconds) }); simulation.agents.forEach((agent, index) => { const before = previous[index]; const state = agent.state; assert.ok(Number.isFinite(state.distance) && Number.isFinite(state.speed)); if (before.active && state.active && before.committed === state.committed) { assert.ok(state.distance >= before.distance - 1e-8, "no reversing or teleporting"); } if (agent.template.kind === "vehicle" && !before.committed && state.committed) { assert.equal(context.signalPhaseAtElapsed(0, seconds, plan).active, "green", "release only on green"); assert.ok(state.distance > before.distance, "release advances position"); releases += 1; } if (agent.template.kind === "pedestrian" && before.active && !state.active) completedCrossings += 1; }); const cars = simulation.agents.filter((agent) => agent.template.kind === "vehicle" && agent.state.active && seconds >= agent.state.spawnDelay).sort((a, b) => a.state.distance - b.state.distance); for (let i = 1; i < cars.length; i += 1) { assert.ok(cars[i].state.distance - cars[i - 1].state.distance >= 4.6 - 0.01, "car bodies never overlap"); } } assert.ok(releases > 15, "traffic keeps releasing across ten cycles"); assert.ok(completedCrossings >= 5, "pedestrians complete crossings instead of freezing"); console.log(`Participant runtime: 600 s passed, ${releases} green releases, ${completedCrossings} completed crossings.`); // Exercise the actual orientation callback at and beyond the open-route end. // Stop after its position samples so this check does not require WebGL/Cesium. const sampledDistances = []; const samplesComplete = new Error("position samples complete"); const orientationContext = vm.createContext({ Cesium: { Cartesian3: class {}, Quaternion: class { static fromAxisAngle() { return {}; } }, Math: { toRadians: (degrees) => degrees * Math.PI / 180 }, HeadingPitchRoll: class {}, CallbackProperty: class { constructor(callback) { this.callback = callback; } }, }, openRoutePositionAtDistance: (route, distance) => { sampledDistances.push(distance); if (sampledDistances.length === 2) throw samplesComplete; }, }); vm.runInContext(functionSource("openRouteOrientationFromState"), orientationContext); for (const distance of [79.5, 80, 81, 200]) { sampledDistances.length = 0; const orientation = orientationContext.openRouteOrientationFromState({ length: 80 }, { distance }, 8, -90); assert.throws(() => orientation.callback(), (error) => error === samplesComplete); assert.ok(sampledDistances[1] > sampledDistances[0], "heading sample remains ahead after exiting the route"); } if (process.argv[2]) { const descriptor = JSON.parse(fs.readFileSync(process.argv[2], "utf8")); context.Cesium.Math = { toRadians: (degrees) => degrees * Math.PI / 180 }; vm.runInContext(functionSource("distanceMeters"), context); seconds = 0; const real = context.createParticipantSimulation({ clock: { onTick: { addEventListener: (fn) => { tick = fn; } } } }, descriptor.participants, new Time(), 8, descriptor.settings, descriptor.signalPlan, 0); const completed = new Map(); function footprint(agent) { const route = agent.route; const distance = agent.state.distance; let index = 1; while (index < route.distances.length - 1 && route.distances[index] < distance) index += 1; const a = route.coordinates[index - 1]; const b = route.coordinates[index]; const fraction = (distance - route.distances[index - 1]) / (route.distances[index] - route.distances[index - 1]); const scaleX = 111195 * Math.cos(30.46288 * Math.PI / 180); const delta = [(b[0] - a[0]) * scaleX, (b[1] - a[1]) * 111195]; const length = Math.hypot(...delta); const forward = delta.map((value) => value / length); return { center: [(a[0] - 114) * scaleX + delta[0] * fraction, (a[1] - 30) * 111195 + delta[1] * fraction], axes: [forward, [-forward[1], forward[0]]], half: [agent.length / 2, agent.template.kind === "vehicle" ? 1 : 0.3] }; } function overlaps(a, b) { const delta = a.center.map((value, index) => value - b.center[index]); const dot = (x, y) => x[0] * y[0] + x[1] * y[1]; return [...a.axes, ...b.axes].every((axis) => { const radius = (box) => box.half.reduce((sum, half, index) => sum + half * Math.abs(dot(box.axes[index], axis)), 0); return Math.abs(dot(delta, axis)) < radius(a) + radius(b) - 0.05; }); } for (let frame = 1; frame <= 12000; frame += 1) { seconds = frame * 0.05; const previous = real.agents.map((agent) => ({ ...agent.state })); tick({ currentTime: new Time(seconds) }); real.agents.forEach((agent, index) => { const before = previous[index]; if (agent.template.kind === "vehicle" && !before.committed && agent.state.committed) { assert.equal(context.signalPhaseAtElapsed(agent.route.stops[0].signal.phaseGroup, seconds, descriptor.signalPlan).active, "green", "real junction releases only on green"); } if ((agent.template.kind === "pedestrian" || agent.template.kind === "bicycle") && !before.committed && agent.state.committed) { const phase = context.signalPhaseAtElapsed(agent.template.phaseGroup, seconds, descriptor.signalPlan); assert.equal(phase.active, "red", "crossing entries follow the paired vehicle red phase"); assert.ok(!phase.initialClearance, "startup all-red does not release crossing users"); assert.ok(!real.agents.some((other) => other.template.kind === "vehicle" && other.state.active && other.state.committed && (other.template.crossingConflicts || []).some((conflict) => conflict.crossingId === agent.template.crossingId && other.state.distance < conflict.distance + other.length + 3)), "crossing entry cannot interrupt a reserved vehicle movement"); } if (agent.template.kind === "vehicle" && before.active && !agent.state.active) { assert.ok(agent.state.distance >= agent.route.length + 120, "vehicles leave only beyond the visible route, not at its short endpoint"); } if (before.active && !agent.state.active) completed.set(agent.template.id, (completed.get(agent.template.id) || 0) + 1); }); if (frame % 5 === 0) { const visible = real.agents.filter((agent) => agent.state.active && seconds >= agent.state.spawnDelay && agent.state.distance >= 0 && agent.state.distance < agent.route.length); for (let i = 0; i < visible.length; i += 1) { for (let j = i + 1; j < visible.length; j += 1) { assert.ok(!overlaps(footprint(visible[i]), footprint(visible[j])), `body overlap at ${seconds}s: ${visible[i].template.id} / ${visible[j].template.id}`); } } } } for (const template of descriptor.participants) { assert.ok(completed.get(template.id) > 0, `${template.id} must clear the junction within 600 s`); } console.log("Real junction: 600 s passed, every movement and crossing completed:", Object.fromEntries(completed)); }