Refactor area preview orchestration

This commit is contained in:
2026-08-04 12:55:20 +08:00
parent 0ce7d1ea5e
commit 396df5127c
16 changed files with 541 additions and 455 deletions

View File

@@ -11,6 +11,13 @@ const {
layerFile,
} = require("./lib/scene-layers");
const { digest: glbDigest } = require("./glb-digest");
const { buildVehicleRoute: buildPreviewVehicleRoute } = require("./lib/vehicle-route");
const { makeVehicleGltf: makePreviewVehicleGltf } = require("./lib/vehicle-model");
const {
cesiumPreviewHtml,
previewSummary,
writeCesiumPreviewSupportFiles,
} = require("./lib/area-preview");
const {
fileRecord,
evaluateGlbBudget,
@@ -479,454 +486,20 @@ function writeCesiumPreview(area) {
});
}
function writeCesiumPreviewSupportFiles(outDir) {
for (const file of ["cesium-preview.css", "cesium-preview.js"]) {
const source = path.join(repoRoot, "scripts", "lib", file);
ensureFile(source, `Cesium preview support file '${file}'`);
fs.copyFileSync(source, path.join(outDir, file));
}
}
function writeVehicleRoute(area) {
const route = buildVehicleRoute(area.input);
const route = buildPreviewVehicleRoute(area.input);
fs.mkdirSync(path.dirname(area.outputs.vehicleRoute), { recursive: true });
fs.writeFileSync(area.outputs.vehicleRoute, `${JSON.stringify(route, null, 2)}\n`);
console.log(`Vehicle route: ${area.outputs.vehicleRoute}`);
}
function writeVehicleModel(area) {
const gltf = makeVehicleGltf();
const gltf = makePreviewVehicleGltf();
fs.mkdirSync(path.dirname(area.outputs.vehicleModel), { recursive: true });
fs.writeFileSync(area.outputs.vehicleModel, `${JSON.stringify(gltf, null, 2)}\n`);
console.log(`Vehicle model: ${area.outputs.vehicleModel}`);
}
function buildVehicleRoute(osmPath) {
const xml = fs.readFileSync(osmPath, "utf8");
const bounds = osmBounds(xml);
const nodes = new Map();
for (const match of xml.matchAll(/<node\b([^>]*)>/g)) {
const attrs = xmlAttrs(match[1]);
if (!attrs.id || attrs.lon === undefined || attrs.lat === undefined) continue;
nodes.set(attrs.id, [Number(attrs.lon), Number(attrs.lat)]);
}
const segments = [];
for (const match of xml.matchAll(/<way\b([^>]*)>([\s\S]*?)<\/way>/g)) {
const attrs = xmlAttrs(match[1]);
const body = match[2];
const tags = {};
for (const tagMatch of body.matchAll(/<tag\b([^>]*)\/?>/g)) {
const tag = xmlAttrs(tagMatch[1]);
if (tag.k) tags[tag.k] = tag.v || "";
}
if (!isCruiseHighway(tags)) continue;
const coords = [];
for (const ndMatch of body.matchAll(/<nd\b([^>]*)\/?>/g)) {
const nd = xmlAttrs(ndMatch[1]);
const coord = nodes.get(nd.ref);
if (coord) coords.push(coord);
}
const runs = splitInBounds(compactCoords(coords), bounds);
let runIndex = 0;
for (const run of runs) {
const lengthMeters = routeLength(run);
if (lengthMeters < 20) continue;
runIndex += 1;
const laneOffsetMeters = 1.3;
const shiftedRun = offsetPolylineRight(run, laneOffsetMeters);
segments.push({
id: runIndex === 1 ? (attrs.id || `way-${segments.length + 1}`) : `${attrs.id || "way"}-${runIndex}`,
name: tags.name || tags.highway || "road",
highway: tags.highway || "",
oneWay: tags.oneway || "",
lengthMeters,
laneOffsetMeters,
coordinates: shiftedRun,
centerlineCoordinates: run,
});
}
}
segments.sort((a, b) => b.lengthMeters - a.lengthMeters);
return {
source: osmPath,
bounds,
generatedAt: new Date().toISOString(),
speedMetersPerSecond: 8.0,
loop: true,
segments,
};
}
function osmBounds(xml) {
const match = xml.match(/<bounds\b([^>]*)\/?>/);
if (!match) return null;
const attrs = xmlAttrs(match[1]);
const bounds = {
minLon: Number(attrs.minlon),
minLat: Number(attrs.minlat),
maxLon: Number(attrs.maxlon),
maxLat: Number(attrs.maxlat),
};
return Object.values(bounds).every(Number.isFinite) ? bounds : null;
}
function xmlAttrs(text) {
const attrs = {};
for (const match of text.matchAll(/([:\w-]+)\s*=\s*("([^"]*)"|'([^']*)')/g)) {
attrs[match[1]] = match[3] !== undefined ? match[3] : match[4];
}
return attrs;
}
function isCruiseHighway(tags) {
const highway = tags.highway || "";
if (!highway) return false;
if (tags.area === "yes") return false;
const blocked = new Set([
"footway", "path", "pedestrian", "steps", "cycleway", "service", "track",
"bridleway", "corridor", "elevator", "platform", "construction",
]);
return !blocked.has(highway);
}
function compactCoords(coords) {
const out = [];
for (const coord of coords) {
const last = out[out.length - 1];
if (!last || last[0] !== coord[0] || last[1] !== coord[1]) {
out.push(coord);
}
}
return out;
}
function offsetPolylineRight(coords, offsetMeters) {
if (coords.length < 2 || offsetMeters === 0) return coords;
const refLat = coords.reduce((sum, coord) => sum + coord[1], 0) / coords.length;
const metersPerLat = 111320.0;
const metersPerLon = 111320.0 * Math.cos(degreesToRadians(refLat));
const points = coords.map((coord) => ({
x: coord[0] * metersPerLon,
y: coord[1] * metersPerLat,
lon: coord[0],
lat: coord[1],
}));
return points.map((point, index) => {
const prev = points[Math.max(0, index - 1)];
const next = points[Math.min(points.length - 1, index + 1)];
let dx = next.x - prev.x;
let dy = next.y - prev.y;
const length = Math.hypot(dx, dy);
if (length < 0.001) return [point.lon, point.lat];
dx /= length;
dy /= length;
const rightX = dy;
const rightY = -dx;
return [
(point.x + rightX * offsetMeters) / metersPerLon,
(point.y + rightY * offsetMeters) / metersPerLat,
];
});
}
function splitInBounds(coords, bounds) {
if (!bounds) return [coords];
const runs = [];
let current = [];
for (const coord of coords) {
if (insideBounds(coord, bounds)) {
current.push(coord);
} else if (current.length) {
if (current.length >= 2) runs.push(current);
current = [];
}
}
if (current.length >= 2) runs.push(current);
return runs;
}
function insideBounds(coord, bounds) {
const pad = 0.00002;
return (
coord[0] >= bounds.minLon - pad &&
coord[0] <= bounds.maxLon + pad &&
coord[1] >= bounds.minLat - pad &&
coord[1] <= bounds.maxLat + pad
);
}
function routeLength(coords) {
let total = 0;
for (let i = 1; i < coords.length; i += 1) {
total += haversineMeters(coords[i - 1], coords[i]);
}
return total;
}
function haversineMeters(a, b) {
const radius = 6371008.8;
const lat1 = degreesToRadians(a[1]);
const lat2 = degreesToRadians(b[1]);
const dLat = degreesToRadians(b[1] - a[1]);
const dLon = degreesToRadians(b[0] - a[0]);
const sinLat = Math.sin(dLat / 2);
const sinLon = Math.sin(dLon / 2);
const h = sinLat * sinLat + Math.cos(lat1) * Math.cos(lat2) * sinLon * sinLon;
return 2 * radius * Math.asin(Math.min(1, Math.sqrt(h)));
}
function degreesToRadians(value) {
return value * Math.PI / 180;
}
function makeVehicleGltf() {
const meshes = [];
const nodes = [];
const bufferParts = [];
const bufferViews = [];
const accessors = [];
function align4(bytes) {
while (bytes.length % 4 !== 0) bytes.push(0);
}
function addBufferView(bytes, target) {
align4(bufferParts);
const offset = bufferParts.length;
bufferParts.push(...bytes);
const view = { buffer: 0, byteOffset: offset, byteLength: bytes.length };
if (target) view.target = target;
bufferViews.push(view);
return bufferViews.length - 1;
}
function floatBytes(values) {
const buffer = Buffer.alloc(values.length * 4);
values.forEach((value, index) => buffer.writeFloatLE(value, index * 4));
return Array.from(buffer);
}
function ushortBytes(values) {
const buffer = Buffer.alloc(values.length * 2);
values.forEach((value, index) => buffer.writeUInt16LE(value, index * 2));
return Array.from(buffer);
}
function addAccessor(bufferView, componentType, count, type, min, max) {
const accessor = { bufferView, componentType, count, type };
if (min) accessor.min = min;
if (max) accessor.max = max;
accessors.push(accessor);
return accessors.length - 1;
}
function addMesh(name, geometry, material) {
const positionView = addBufferView(floatBytes(geometry.positions), 34962);
const indexView = addBufferView(ushortBytes(geometry.indices), 34963);
const positionAccessor = addAccessor(
positionView,
5126,
geometry.positions.length / 3,
"VEC3",
geometry.min,
geometry.max,
);
const indexAccessor = addAccessor(indexView, 5123, geometry.indices.length, "SCALAR");
meshes.push({
name,
primitives: [{
attributes: { POSITION: positionAccessor },
indices: indexAccessor,
material,
}],
});
nodes.push({ name, mesh: meshes.length - 1 });
}
addMesh("body", cuboid(0, 0, 0.72, 4.6, 1.9, 0.9), 0);
addMesh("hood", cuboid(1.35, 0, 1.1, 1.25, 1.74, 0.38), 0);
addMesh("cabin", cuboid(-0.55, 0, 1.42, 1.75, 1.55, 0.82), 1);
addMesh("rear", cuboid(-1.65, 0, 1.08, 0.95, 1.78, 0.42), 0);
addMesh("front_windshield", cuboid(0.28, 0, 1.58, 0.12, 1.42, 0.58), 2);
addMesh("left_window", cuboid(-0.55, -0.82, 1.52, 1.25, 0.08, 0.48), 2);
addMesh("right_window", cuboid(-0.55, 0.82, 1.52, 1.25, 0.08, 0.48), 2);
for (const x of [-1.55, 1.45]) {
for (const y of [-1.02, 1.02]) {
addMesh(`wheel_${x}_${y}`, cylinderY(x, y, 0.46, 0.38, 0.32, 16), 3);
addMesh(`hub_${x}_${y}`, cylinderY(x, y, 0.46, 0.2, 0.34, 12), 4);
}
}
addMesh("left_headlight", cuboid(2.36, -0.48, 0.9, 0.08, 0.32, 0.16), 5);
addMesh("right_headlight", cuboid(2.36, 0.48, 0.9, 0.08, 0.32, 0.16), 5);
addMesh("left_tail", cuboid(-2.36, -0.55, 0.9, 0.08, 0.28, 0.16), 6);
addMesh("right_tail", cuboid(-2.36, 0.55, 0.9, 0.08, 0.28, 0.16), 6);
const buffer = Buffer.from(bufferParts);
return {
asset: { version: "2.0", generator: "osm-asset-pipeline vehicle preview" },
scene: 0,
scenes: [{ nodes: nodes.map((_, index) => index) }],
nodes,
meshes,
buffers: [{
byteLength: buffer.length,
uri: `data:application/octet-stream;base64,${buffer.toString("base64")}`,
}],
bufferViews,
accessors,
materials: [
material("paint red", [0.82, 0.05, 0.035, 1], 0.55, 0.25),
material("dark roof", [0.08, 0.08, 0.085, 1], 0.45, 0.35),
material("glass", [0.04, 0.12, 0.16, 0.82], 0.18, 0.08),
material("tire", [0.015, 0.014, 0.013, 1], 0.75, 0.65),
material("wheel hub", [0.72, 0.72, 0.68, 1], 0.35, 0.85),
material("headlight", [1.0, 0.92, 0.62, 1], 0.12, 0.0),
material("tail light", [0.95, 0.03, 0.03, 1], 0.25, 0.0),
],
};
}
function material(name, color, roughness, metallic) {
return {
name,
pbrMetallicRoughness: {
baseColorFactor: color,
roughnessFactor: roughness,
metallicFactor: metallic,
},
};
}
function cuboid(cx, lateral, up, sx, width, height) {
const x0 = cx - sx / 2;
const x1 = cx + sx / 2;
const y0 = up - height / 2;
const y1 = up + height / 2;
const z0 = lateral - width / 2;
const z1 = lateral + width / 2;
const positions = [
x0, y0, z0, x1, y0, z0, x1, y1, z0, x0, y1, z0,
x0, y0, z1, x1, y0, z1, x1, y1, z1, x0, y1, z1,
];
const indices = [
0, 1, 2, 0, 2, 3, 4, 6, 5, 4, 7, 6,
0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2,
2, 6, 7, 2, 7, 3, 3, 7, 4, 3, 4, 0,
];
return { positions, indices, min: [x0, y0, z0], max: [x1, y1, z1] };
}
function cylinderY(cx, lateral, up, radius, width, segments) {
const positions = [];
const indices = [];
const z0 = lateral - width / 2;
const z1 = lateral + width / 2;
for (const z of [z0, z1]) {
positions.push(cx, up, z);
for (let i = 0; i < segments; i += 1) {
const angle = 2 * Math.PI * i / segments;
positions.push(cx + Math.cos(angle) * radius, up + Math.sin(angle) * radius, z);
}
}
const center0 = 0;
const center1 = segments + 1;
for (let i = 0; i < segments; i += 1) {
const a0 = center0 + 1 + i;
const b0 = center0 + 1 + ((i + 1) % segments);
const a1 = center1 + 1 + i;
const b1 = center1 + 1 + ((i + 1) % segments);
indices.push(center0, b0, a0);
indices.push(center1, a1, b1);
indices.push(a0, b0, b1, a0, b1, a1);
}
return {
positions,
indices,
min: [cx - radius, up - radius, z0],
max: [cx + radius, up + radius, z1],
};
}
function cesiumPreviewHtml(glbName, metadataName, routeName, vehicleModelName, areaId) {
const previewConfig = {
areaId,
glbName,
metadataName,
routeName,
vehicleModelName,
};
return `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(areaId)} Cesium Preview</title>
<script src="https://cdn.jsdelivr.net/npm/cesium@1.121.1/Build/Cesium/Cesium.js"></script>
<link href="https://cdn.jsdelivr.net/npm/cesium@1.121.1/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
<link href="cesium-preview.css" rel="stylesheet">
</head>
<body>
<div id="cesiumContainer"></div>
<div id="controls">
<div class="control-group">
<button id="toggleCruise">Pause</button>
<button id="toggleFollow">Follow</button>
<label>Vehicle <select id="vehicleSelect"></select></label>
<label>Speed <input id="speedControl" type="range" min="2" max="22" step="1" value="8"></label>
<span id="speedLabel">8 m/s</span>
</div>
<div class="control-group">
<label><input id="toggleScene" type="checkbox" checked> Scene</label>
<span id="assetToggles" class="control-subgroup"></span>
<label><input id="toggleRoutes" type="checkbox" checked> Routes</label>
<label><input id="toggleVehicles" type="checkbox" checked> Vehicles</label>
<label><input id="toggleFps" type="checkbox"> FPS</label>
<label><input id="toggleDiagnostics" type="checkbox" checked> Info</label>
</div>
<div class="control-group">
<button data-camera="overview">Overview</button>
<button data-camera="oblique">Oblique</button>
<button data-camera="detail">Detail</button>
<button data-camera="route">Route</button>
</div>
</div>
<div id="diagnostics">Loading diagnostics...</div>
<div id="status">Loading ${escapeHtml(glbName)}...</div>
<div id="loadingOverlay">
<div class="loading-card">
<div class="loading-spinner" aria-hidden="true"></div>
<div class="loading-copy">
<strong>Loading scene</strong>
<span>${escapeHtml(areaId)}</span>
</div>
<div class="loading-bar" aria-hidden="true"><span></span></div>
</div>
</div>
<script>window.OSM_ASSET_PREVIEW_CONFIG = ${escapeScriptJson(JSON.stringify(previewConfig))};</script>
<script src="cesium-preview.js"></script>
</body>
</html>
`;
}
function escapeHtml(value) {
return String(value)
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
function escapeScriptJson(value) {
return String(value)
.replaceAll("<", "\\u003c")
.replaceAll(">", "\\u003e")
.replaceAll("&", "\\u0026")
.replaceAll("\u2028", "\\u2028")
.replaceAll("\u2029", "\\u2029");
}
function sceneGeojsonRecords(area) {
const records = {};
for (const layer of SCENE_LAYERS) {
@@ -951,14 +524,3 @@ function featureCount(file) {
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
return Array.isArray(parsed.features) ? parsed.features.length : null;
}
function previewSummary(area) {
const route = JSON.parse(fs.readFileSync(area.outputs.vehicleRoute, "utf8"));
return {
glbName: path.basename(area.outputs.glb),
metadataName: path.basename(area.outputs.metadata),
routeName: path.basename(area.outputs.vehicleRoute),
vehicleModelName: path.basename(area.outputs.vehicleModel),
routeSegments: Array.isArray(route.segments) ? route.segments.length : null,
};
}