draw routes

This commit is contained in:
Evan Scamehorn
2025-11-26 21:26:41 -06:00
parent 059a58fbf7
commit 45b8811767
4 changed files with 485 additions and 332 deletions

View File

@@ -1,6 +1,10 @@
import osmnx as ox
import json
import os
import networkx as nx
from shapely.ops import unary_union
from shapely.geometry import Polygon, MultiPolygon
import re
# ==========================================
# 1. Configuration
@@ -8,48 +12,31 @@ import os
PLACE_NAME = "Wisconsin State Capitol, Madison, USA"
DIST = 3000
# ==========================================
# 2. Data Fetching
# ==========================================
print(f"Downloading data for {PLACE_NAME}...")
# Define tags for different layers
tags = {
"building": True,
"natural": ["water", "bay", "coastline"],
"landuse": ["grass", "forest", "park", "recreation_ground"],
"leisure": ["park", "garden"],
"highway": True,
# Road width settings (meters)
LANE_WIDTH_DEFAULT = 3.5
DEFAULT_WIDTHS = {
"motorway": 12,
"trunk": 11,
"primary": 10,
"secondary": 9,
"tertiary": 8,
"residential": 6,
"service": 4,
"unclassified": 5,
"cycleway": 2,
"footway": 1.5,
"path": 1.5,
}
try:
# OSMNX v2.0+
gdf = ox.features.features_from_address(PLACE_NAME, tags=tags, dist=DIST)
except AttributeError:
# OSMNX < v2.0
gdf = ox.features_from_address(PLACE_NAME, tags=tags, dist=DIST)
# ==========================================
# 3. Projection & Normalization
# 2. Helpers
# ==========================================
print("Projecting to local grid...")
gdf_proj = gdf.to_crs(gdf.estimate_utm_crs())
# Calculate center for (0,0,0) normalization
center_x = gdf_proj.geometry.centroid.x.mean()
center_y = gdf_proj.geometry.centroid.y.mean()
# ==========================================
# 4. Processing Functions
# ==========================================
def get_height(row):
"""Estimates building height from tags."""
h = 10.0 # Default
"""Estimates building height."""
h = 8.0
if "height" in row and str(row["height"]).lower() != "nan":
try:
# Extract numeric part
clean = "".join(
filter(lambda x: x.isdigit() or x == ".", str(row["height"]))
)
@@ -67,81 +54,173 @@ def get_height(row):
return round(h, 1)
def parse_polygon(geom):
"""Extracts exterior coordinates from a Polygon."""
if geom.is_empty:
return []
coords = list(geom.exterior.coords)
# Simplify slightly to reduce vertex count if needed, or keep raw
return [[round(x - center_x, 1), round(y - center_y, 1)] for x, y in coords]
def estimate_road_width(row):
"""Estimates width with US-unit safety checks."""
# 1. Explicit width tag
for key in ["width", "width:carriageway", "est_width"]:
if key in row and str(row[key]) != "nan":
val_str = str(row[key]).lower()
try:
nums = re.findall(r"[-+]?\d*\.\d+|\d+", val_str)
if nums:
val = float(nums[0])
if "'" in val_str or "ft" in val_str or "feet" in val_str:
val *= 0.3048
elif val > 50: # Sanity check for feet without units
val *= 0.3048
return val
except:
pass
# 2. Lanes
if "lanes" in row and str(row["lanes"]) != "nan":
try:
clean = re.findall(r"\d+", str(row["lanes"]))
if clean:
lanes = int(clean[0])
lanes = max(1, min(lanes, 6))
return lanes * LANE_WIDTH_DEFAULT
except:
pass
# 3. Default based on type
highway = row.get("highway", "residential")
if isinstance(highway, list):
highway = highway[0]
return DEFAULT_WIDTHS.get(highway, 4.0)
def parse_linestring(geom):
"""Extracts coordinates from a LineString."""
def parse_geometry(geom, center_x, center_y):
"""Parses geometry into {outer, holes} structure."""
if geom.is_empty:
return []
coords = list(geom.coords)
return [[round(x - center_x, 1), round(y - center_y, 1)] for x, y in coords]
polys = []
if geom.geom_type == "Polygon":
source_geoms = [geom]
elif geom.geom_type == "MultiPolygon":
source_geoms = geom.geoms
else:
return []
for poly in source_geoms:
outer = [
[round(x - center_x, 2), round(y - center_y, 2)]
for x, y in poly.exterior.coords
]
holes = []
for interior in poly.interiors:
hole_coords = [
[round(x - center_x, 2), round(y - center_y, 2)]
for x, y in interior.coords
]
holes.append(hole_coords)
polys.append({"outer": outer, "holes": holes})
return polys
def parse_line_points(geom, center_x, center_y):
"""Simple parser for LineStrings (Routing Graph)."""
if geom.geom_type == "LineString":
return [
[round(x - center_x, 2), round(y - center_y, 2)] for x, y in geom.coords
]
return []
# ==========================================
# 5. Categorization Loop
# 3. Execution
# ==========================================
output_data = {"buildings": [], "water": [], "parks": [], "roads": []}
print(f"1. Downloading Data for: {PLACE_NAME}...")
print("Processing geometries...")
tags_visual = {
"building": True,
"natural": ["water", "bay"],
"leisure": ["park", "garden"],
"landuse": ["grass", "forest", "park"],
}
gdf_visual = ox.features.features_from_address(PLACE_NAME, tags=tags_visual, dist=DIST)
for idx, row in gdf_proj.iterrows():
geom = row.geometry
print(" Downloading Road Graph...")
G = ox.graph.graph_from_address(PLACE_NAME, dist=DIST, network_type="drive")
gdf_nodes, gdf_edges = ox.graph_to_gdfs(G)
# Handle MultiPolygons by iterating over them
geoms = [geom] if geom.geom_type in ["Polygon", "LineString"] else []
if geom.geom_type == "MultiPolygon":
geoms = list(geom.geoms)
elif geom.geom_type == "MultiLineString":
geoms = list(geom.geoms)
print("2. Projecting Coordinates...")
utm_crs = gdf_visual.estimate_utm_crs()
gdf_visual = gdf_visual.to_crs(utm_crs)
gdf_edges = gdf_edges.to_crs(utm_crs)
gdf_nodes = gdf_nodes.to_crs(utm_crs)
for sub_geom in geoms:
# 1. BUILDINGS
center_x = gdf_visual.geometry.centroid.x.mean()
center_y = gdf_visual.geometry.centroid.y.mean()
output_visual = {"buildings": [], "water": [], "parks": [], "roads": []}
output_routing = {"nodes": {}, "edges": []}
print("3. Processing Visual Layers...")
for idx, row in gdf_visual.iterrows():
polygons = parse_geometry(row.geometry, center_x, center_y)
for poly_data in polygons:
# 1. Buildings
if "building" in row and str(row["building"]) != "nan":
if sub_geom.geom_type == "Polygon":
output_data["buildings"].append(
{"shape": parse_polygon(sub_geom), "height": get_height(row)}
output_visual["buildings"].append(
{"shape": poly_data, "height": get_height(row)}
)
# 2. WATER
elif ("natural" in row and row["natural"] in tags["natural"]) or (
# 2. Water (Explicit check for NaN)
elif ("natural" in row and str(row["natural"]) != "nan") or (
"water" in row and str(row["water"]) != "nan"
):
if sub_geom.geom_type == "Polygon":
output_data["water"].append({"shape": parse_polygon(sub_geom)})
output_visual["water"].append({"shape": poly_data})
# 3. PARKS / GREENSPACE
elif ("leisure" in row and row["leisure"] in tags["leisure"]) or (
"landuse" in row and row["landuse"] in tags["landuse"]
):
if sub_geom.geom_type == "Polygon":
output_data["parks"].append({"shape": parse_polygon(sub_geom)})
# 3. Parks (Fallback)
else:
output_visual["parks"].append({"shape": poly_data})
# 4. ROADS
elif "highway" in row and str(row["highway"]) != "nan":
if sub_geom.geom_type == "LineString":
output_data["roads"].append({"path": parse_linestring(sub_geom)})
print(" Buffering roads...")
road_polys = []
for idx, row in gdf_edges.iterrows():
width = estimate_road_width(row)
buffered = row.geometry.buffer(width / 2, cap_style=2, join_style=2)
road_polys.append(buffered)
# ==========================================
# 6. Save File
# ==========================================
output_path = os.path.join(os.path.dirname(__file__), "../public/city_data.json")
os.makedirs(os.path.dirname(output_path), exist_ok=True)
if road_polys:
print(" Merging road polygons...")
merged_roads = unary_union(road_polys)
road_shapes = parse_geometry(merged_roads, center_x, center_y)
for shape in road_shapes:
output_visual["roads"].append({"shape": shape})
with open(output_path, "w") as f:
json.dump(output_data, f)
print("4. Processing Routing Graph...")
for node_id, row in gdf_nodes.iterrows():
output_routing["nodes"][int(node_id)] = {
"x": round(row.geometry.x - center_x, 2),
"y": round(row.geometry.y - center_y, 2),
}
print(
f"Exported:"
f"\n Buildings: {len(output_data['buildings'])}"
f"\n Roads: {len(output_data['roads'])}"
f"\n Water: {len(output_data['water'])}"
f"\n Parks: {len(output_data['parks'])}"
for u, v, k in G.edges(keys=True):
try:
row = gdf_edges.loc[(u, v, k)]
if isinstance(row, (type(gdf_edges),)):
row = row.iloc[0]
except KeyError:
continue
output_routing["edges"].append(
{
"u": int(u),
"v": int(v),
"oneway": bool(row.get("oneway", False)),
"points": parse_line_points(row.geometry, center_x, center_y),
}
)
print(f"Saved to {output_path}")
out_dir = os.path.join(os.path.dirname(__file__), "../public")
os.makedirs(out_dir, exist_ok=True)
with open(os.path.join(out_dir, "city_data.json"), "w") as f:
json.dump(output_visual, f)
with open(os.path.join(out_dir, "routing_graph.json"), "w") as f:
json.dump(output_routing, f)
print(f"Done! Exported to {out_dir}")

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -3,302 +3,375 @@ import { MapControls } from 'three/addons/controls/MapControls.js';
import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js';
// ==========================================
// 1. Configuration & Constants
// 1. Configuration
// ==========================================
const SETTINGS = {
colors: {
background: 0xe0e0e0, // Lighter fog
ground: 0xdddddd,
building: 0xffffff,
water: 0x4fa4e4,
park: 0x98d98e,
background: 0xE6E6E6,
ground: 0xDDDDDD,
building: 0xFFFFFF,
water: 0xAADAFF,
park: 0xC3E6CB,
road: 0x999999,
sun: 0xffffff,
ambient: 0x777777,
pathStart: 0x00FF00,
pathEnd: 0xFF0000,
route: 0x2563EB,
},
camera: {
fov: 45, // Narrower FOV for better city look
near: 1,
far: 20000,
initialPos: { x: 0, y: 600, z: 800 }
},
shadows: {
enabled: true,
mapSize: 4096,
areaSize: 1500,
bias: -0.0001
},
dataUrl: './city_data.json'
files: {
visual: './city_data.json',
routing: './routing_graph.json'
}
};
let scene, camera, renderer, controls, sunLight;
let scene, camera, renderer, controls, raycaster;
let mouse = new THREE.Vector2();
let routingData = null;
let cityData = null;
// ==========================================
// 2. Initialization
// ==========================================
// Interaction State
let startNode = null;
let endNode = null;
let markers = { start: null, end: null, pathMesh: null };
function init() {
setupScene();
setupLighting();
createGround();
setupControls();
loadCityData();
setupInteractions();
Promise.all([
fetch(SETTINGS.files.visual).then(r => r.json()),
fetch(SETTINGS.files.routing).then(r => r.json())
]).then(([visual, routing]) => {
cityData = visual;
routingData = routing;
renderCity(cityData);
prepareGraph(routingData); // This now fixes the coordinates!
});
window.addEventListener('resize', onWindowResize);
animate();
}
// ==========================================
// 2. Data Preparation & Coordinate Fix
// ==========================================
function prepareGraph(data) {
// We must FLIP the Y coordinate of the graph data to -Z
// because our visual map is rotated -90deg on the X axis.
data.adjacency = {};
// 1. Fix Nodes
for (let key in data.nodes) {
data.nodes[key].y = -data.nodes[key].y; // FLIP Y to Negative
}
// 2. Fix Edges
data.edges.forEach((edge, index) => {
// Flip geometry points
if (edge.points) {
edge.points.forEach(p => { p[1] = -p[1]; });
}
// Build Adjacency List
if (!data.adjacency[edge.u]) data.adjacency[edge.u] = [];
data.adjacency[edge.u].push({
to: edge.v,
cost: edge.length || 1,
edgeIndex: index
});
if (!edge.oneway) {
if (!data.adjacency[edge.v]) data.adjacency[edge.v] = [];
data.adjacency[edge.v].push({
to: edge.u,
cost: edge.length || 1,
edgeIndex: index,
isReverse: true
});
}
});
}
// ==========================================
// 3. Scene Setup
// ==========================================
function setupScene() {
scene = new THREE.Scene();
scene.background = new THREE.Color(SETTINGS.colors.background);
scene.fog = new THREE.FogExp2(SETTINGS.colors.background, 0.0001);
scene.fog = new THREE.FogExp2(SETTINGS.colors.background, 0.0002);
camera = new THREE.PerspectiveCamera(
SETTINGS.camera.fov,
window.innerWidth / window.innerHeight,
SETTINGS.camera.near,
SETTINGS.camera.far
);
camera.position.set(
SETTINGS.camera.initialPos.x,
SETTINGS.camera.initialPos.y,
SETTINGS.camera.initialPos.z
);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 20000);
camera.position.set(0, 800, 800);
renderer = new THREE.WebGLRenderer({
antialias: true,
logarithmicDepthBuffer: true
});
renderer = new THREE.WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = SETTINGS.shadows.enabled;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
}
/**
* Creates ambient and directional lighting.
* Configures shadow properties for the directional light.
*/
function setupLighting() {
const ambient = new THREE.HemisphereLight(SETTINGS.colors.sun, SETTINGS.colors.ground, 0.6);
const ambient = new THREE.HemisphereLight(0xffffff, 0x555555, 0.7);
scene.add(ambient);
sunLight = new THREE.DirectionalLight(SETTINGS.colors.sun, 2.0);
sunLight.position.set(100, 500, 200);
sunLight.castShadow = true;
const dirLight = new THREE.DirectionalLight(0xffffff, 1.5);
dirLight.position.set(500, 1000, 500);
dirLight.castShadow = true;
dirLight.shadow.mapSize.set(2048, 2048);
dirLight.shadow.camera.left = -1500;
dirLight.shadow.camera.right = 1500;
dirLight.shadow.camera.top = 1500;
dirLight.shadow.camera.bottom = -1500;
scene.add(dirLight);
sunLight.shadow.mapSize.set(SETTINGS.shadows.mapSize, SETTINGS.shadows.mapSize);
const d = SETTINGS.shadows.areaSize;
sunLight.shadow.camera.left = -d;
sunLight.shadow.camera.right = d;
sunLight.shadow.camera.top = d;
sunLight.shadow.camera.bottom = -d;
const plane = new THREE.Mesh(
new THREE.PlaneGeometry(10000, 10000),
new THREE.MeshLambertMaterial({ color: SETTINGS.colors.ground })
);
plane.rotation.x = -Math.PI / 2;
plane.position.y = -0.5;
plane.name = "GROUND";
plane.receiveShadow = true;
scene.add(plane);
sunLight.shadow.camera.near = 0.5;
sunLight.shadow.camera.far = 4500;
sunLight.shadow.bias = SETTINGS.shadows.bias;
scene.add(sunLight);
}
function setupControls() {
controls = new MapControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.minDistance = 50;
controls.maxDistance = 3000;
controls.maxPolarAngle = Math.PI / 2 - 0.1; // Don't go below ground
controls.enableDamping = true;
controls.maxPolarAngle = Math.PI / 2 - 0.1;
raycaster = new THREE.Raycaster();
}
function createGround() {
const geom = new THREE.PlaneGeometry(10000, 10000);
const mat = new THREE.MeshLambertMaterial({ color: SETTINGS.colors.ground });
const mesh = new THREE.Mesh(geom, mat);
mesh.rotation.x = -Math.PI / 2;
mesh.position.y = -0.5; // Slightly below features
mesh.receiveShadow = true;
scene.add(mesh);
}
// ==========================================
// 3. Data Processing & Mesh Generation
// ==========================================
function loadCityData() {
fetch(SETTINGS.dataUrl)
.then(res => res.json())
.then(data => {
console.log("City data loaded. Generating geometry...");
generateCity(data);
})
.catch(err => console.error("Error loading city data:", err));
}
function generateCity(data) {
// 1. Water (Flat Polygons)
if (data.water && data.water.length) {
createPolygonLayer(data.water, SETTINGS.colors.water, 0, 0.1);
}
// 2. Parks (Flat Polygons)
if (data.parks && data.parks.length) {
createPolygonLayer(data.parks, SETTINGS.colors.park, 0, 0.2);
}
// 3. Roads (Lines)
if (data.roads && data.roads.length) {
createRoadLayer(data.roads, SETTINGS.colors.road, 0.3);
}
// 4. Buildings (Extruded Polygons)
if (data.buildings && data.buildings.length) {
createBuildingLayer(data.buildings, SETTINGS.colors.building);
}
}
/**
* Creates flat meshes for things like water or parks.
* Uses BufferGeometryUtils to merge them into one draw call.
*/
function createPolygonLayer(items, color, height, yOffset) {
const geometries = [];
items.forEach(item => {
const shape = createShapeFromPoints(item.shape);
const geometry = new THREE.ShapeGeometry(shape);
// Rotate to lie flat on XZ plane
geometry.rotateX(-Math.PI / 2);
geometry.translate(0, yOffset, 0); // Lift slightly to avoid z-fighting
geometries.push(geometry);
});
if (geometries.length === 0) return;
const mergedGeometry = BufferGeometryUtils.mergeGeometries(geometries);
const material = new THREE.MeshLambertMaterial({ color: color, side: THREE.DoubleSide });
const mesh = new THREE.Mesh(mergedGeometry, material);
mesh.receiveShadow = true;
scene.add(mesh);
}
/**
* Creates extruded meshes for buildings.
*/
function createBuildingLayer(buildings, color) {
const geometries = [];
buildings.forEach(b => {
const shape = createShapeFromPoints(b.shape);
// Extrude Settings
const extrudeSettings = {
depth: b.height,
bevelEnabled: false,
};
const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
geometry.rotateX(-Math.PI / 2);
geometries.push(geometry);
});
if (geometries.length === 0) return;
const mergedGeometry = BufferGeometryUtils.mergeGeometries(geometries);
// Center the geometry to optimize bounding sphere calculations
mergedGeometry.computeBoundingSphere();
const material = new THREE.MeshStandardMaterial({
color: color,
roughness: 0.6,
metalness: 0.1
});
const mesh = new THREE.Mesh(mergedGeometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
}
/**
* Creates simple lines for roads.
* Note: THREE.Line doesn't cast shadows easily, but it's performant.
*/
function createRoadLayer(roads, color, yOffset) {
const positions = [];
roads.forEach(road => {
const path = road.path;
for (let i = 0; i < path.length - 1; i++) {
positions.push(path[i][0], path[i][1], 0);
positions.push(path[i + 1][0], path[i + 1][1], 0);
}
});
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
geometry.rotateX(-Math.PI / 2);
geometry.translate(0, yOffset, 0);
const material = new THREE.LineBasicMaterial({
color: color,
opacity: 0.8,
transparent: true
});
const lineSegments = new THREE.LineSegments(geometry, material);
scene.add(lineSegments);
}
/**
* Helper to convert array of [x,z] points into a THREE.Shape
*/
function createShapeFromPoints(points) {
const shape = new THREE.Shape();
if (!points || points.length === 0) return shape;
// First point
shape.moveTo(points[0][0], points[0][1]);
// Subsequent points
for (let i = 1; i < points.length; i++) {
shape.lineTo(points[i][0], points[i][1]);
}
return shape;
}
// ==========================================
// 4. Animation Loop
// ==========================================
function onWindowResize() {
function setupInteractions() {
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
window.addEventListener('pointerdown', (event) => {
if (event.button !== 0) return;
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(scene.children);
const hit = intersects.find(obj => obj.object.name === "GROUND");
if (hit && routingData) {
// Pass the Hit Point (X, Z) directly.
// Z corresponds to our flipped Y in the graph.
handleMapClick(hit.point.x, hit.point.z);
}
});
}
function updateSunPosition() {
if (sunLight && camera) {
// Keep shadow map centered around camera
sunLight.position.x = camera.position.x + 100;
sunLight.position.z = camera.position.z + 200;
sunLight.target.position.set(camera.position.x, 0, camera.position.z);
sunLight.target.updateMatrixWorld();
// ==========================================
// 4. Visual Rendering
// ==========================================
function renderCity(data) {
const createLayer = (items, color, height, lift, isExtruded) => {
if (!items || !items.length) return;
const geometries = [];
items.forEach(item => {
const polyData = item.shape;
if (!polyData || !polyData.outer || polyData.outer.length < 3) return;
const shape = new THREE.Shape();
shape.moveTo(polyData.outer[0][0], polyData.outer[0][1]);
for (let i = 1; i < polyData.outer.length; i++) shape.lineTo(polyData.outer[i][0], polyData.outer[i][1]);
if (polyData.holes) {
polyData.holes.forEach(holePts => {
if (holePts.length < 3) return;
const holePath = new THREE.Path();
holePath.moveTo(holePts[0][0], holePts[0][1]);
for (let j = 1; j < holePts.length; j++) holePath.lineTo(holePts[j][0], holePts[j][1]);
shape.holes.push(holePath);
});
}
if (isExtruded) {
const geom = new THREE.ExtrudeGeometry(shape, { depth: item.height || height, bevelEnabled: false });
geom.rotateX(-Math.PI / 2);
geometries.push(geom);
} else {
const geom = new THREE.ShapeGeometry(shape);
geom.rotateX(-Math.PI / 2);
geom.translate(0, lift, 0);
geometries.push(geom);
}
});
if (!geometries.length) return;
const merged = BufferGeometryUtils.mergeGeometries(geometries);
const mat = new THREE.MeshStandardMaterial({ color: color, roughness: 0.8, side: THREE.DoubleSide });
const mesh = new THREE.Mesh(merged, mat);
mesh.receiveShadow = true;
if (isExtruded) mesh.castShadow = true;
scene.add(mesh);
};
createLayer(data.water, SETTINGS.colors.water, 0, 0.1, false);
createLayer(data.parks, SETTINGS.colors.park, 0, 0.2, false);
createLayer(data.roads, SETTINGS.colors.road, 0, 0.3, false);
createLayer(data.buildings, SETTINGS.colors.building, 10, 0, true);
}
// ==========================================
// 5. Routing Logic (A*)
// ==========================================
function handleMapClick(x, z) {
const nearestId = findNearestNode(x, z);
if (!startNode) {
startNode = nearestId;
placeMarker('start', routingData.nodes[nearestId], SETTINGS.colors.pathStart);
if (markers.end) { scene.remove(markers.end); markers.end = null; }
if (markers.pathMesh) { scene.remove(markers.pathMesh); markers.pathMesh = null; }
endNode = null;
} else {
endNode = nearestId;
placeMarker('end', routingData.nodes[nearestId], SETTINGS.colors.pathEnd);
const path = computePathAStar(startNode, endNode);
if (path) drawPath(path);
startNode = null;
}
}
function findNearestNode(x, z) {
let closestId = null;
let minDist = Infinity;
for (const [id, node] of Object.entries(routingData.nodes)) {
// node.y is already flipped to match Z
const dx = node.x - x;
const dz = node.y - z;
const d2 = dx * dx + dz * dz;
if (d2 < minDist) {
minDist = d2;
closestId = parseInt(id);
}
}
return closestId;
}
function computePathAStar(start, end) {
const openSet = new Set([start]);
const cameFrom = {};
const gScore = {};
const fScore = {};
gScore[start] = 0;
fScore[start] = heuristic(start, end);
while (openSet.size > 0) {
let current = null;
let minF = Infinity;
for (const node of openSet) {
const score = fScore[node] !== undefined ? fScore[node] : Infinity;
if (score < minF) { minF = score; current = node; }
}
if (current === end) return reconstructPath(cameFrom, current);
openSet.delete(current);
const neighbors = routingData.adjacency[current] || [];
for (const neighbor of neighbors) {
const tentativeG = gScore[current] + neighbor.cost;
if (tentativeG < (gScore[neighbor.to] !== undefined ? gScore[neighbor.to] : Infinity)) {
cameFrom[neighbor.to] = { prev: current, edgeIdx: neighbor.edgeIndex, isReverse: neighbor.isReverse };
gScore[neighbor.to] = tentativeG;
fScore[neighbor.to] = tentativeG + heuristic(neighbor.to, end);
openSet.add(neighbor.to);
}
}
}
return null;
}
function heuristic(a, b) {
const nA = routingData.nodes[a];
const nB = routingData.nodes[b];
return Math.sqrt((nA.x - nB.x) ** 2 + (nA.y - nB.y) ** 2);
}
function reconstructPath(cameFrom, current) {
const edges = [];
while (current in cameFrom) {
const data = cameFrom[current];
edges.push({ edgeData: routingData.edges[data.edgeIdx], isReverse: data.isReverse });
current = data.prev;
}
return edges.reverse();
}
// ==========================================
// 6. Path Drawing
// ==========================================
function drawPath(pathEdges) {
if (markers.pathMesh) scene.remove(markers.pathMesh);
const points = [];
const ROAD_OFFSET = 3.0;
pathEdges.forEach(step => {
const rawPoints = step.edgeData.points;
// Map raw array to Vectors. Note: p[1] is already flipped to Z space
let segmentPoints = rawPoints.map(p => new THREE.Vector2(p[0], p[1]));
if (step.isReverse) segmentPoints.reverse();
// Calculate offset for "Right Hand Drive"
const offsetSegment = getOffsetPath(segmentPoints, ROAD_OFFSET);
offsetSegment.forEach(p => {
// p.x is X, p.y is Z (since we flipped it)
points.push(new THREE.Vector3(p.x, 0.5, p.y));
});
});
const curve = new THREE.CatmullRomCurve3(points);
const tubeGeom = new THREE.TubeGeometry(curve, points.length, 1.5, 6, false);
const tubeMat = new THREE.MeshBasicMaterial({ color: SETTINGS.colors.route });
markers.pathMesh = new THREE.Mesh(tubeGeom, tubeMat);
scene.add(markers.pathMesh);
}
function getOffsetPath(points, offset) {
if (points.length < 2) return points;
const newPath = [];
for (let i = 0; i < points.length - 1; i++) {
const p1 = points[i];
const p2 = points[i + 1];
const dir = new THREE.Vector2().subVectors(p2, p1).normalize();
// Normal for Right side: (-y, x)
// Since our Coordinate system is flipped (Z is inverted), (-y, x) works as "Right"
const normal = new THREE.Vector2(-dir.y, dir.x);
const off = normal.multiplyScalar(offset);
newPath.push(new THREE.Vector2().addVectors(p1, off));
if (i === points.length - 2) newPath.push(new THREE.Vector2().addVectors(p2, off));
}
return newPath;
}
function placeMarker(type, node, color) {
if (markers[type]) scene.remove(markers[type]);
const geom = new THREE.SphereGeometry(4);
const mat = new THREE.MeshBasicMaterial({ color: color });
const mesh = new THREE.Mesh(geom, mat);
// node.y is now Z
mesh.position.set(node.x, 2, node.y);
markers[type] = mesh;
scene.add(mesh);
}
function animate() {
requestAnimationFrame(animate);
controls.update();
updateSunPosition();
renderer.render(scene, camera);
}
// Start
init();