穿過波士頓摩天大樓看見 T:我們如何在 BostonHacks 打造 AboveGround
Seeing the T Through Boston's Skyscrapers: How We Built AboveGround at BostonHacks
四人團隊在 BostonHacks 2026 打造 AboveGround,以 3D 地圖即時呈現波士頓地鐵列車、車站及行程。為免列車和路線被建築物遮擋,團隊調整 Mapbox 圖層的遮擋透明度,並為 three.js 模型加入額外的透視繪製。
This is a submission for the MLH x DEV Writing Challenge
Every MBTA rider knows the feeling. The board says 4 minutes, then 12, then the train just disappears, and nobody tells you why.
At BostonHacks 2026, four of us built AboveGround: a live 3D map of Boston's subway that shows what's happening, why, and what to do next. It won the Transit Gamification Track Prize and the [MLH] Build Your Hackathon A-Team with SpaceXSI prize.
This post is mostly about one bug that almost broke the whole idea. In the middle of the night before judging, we zoomed in on downtown Boston and our trains vanished behind the buildings.
What I Built
AboveGround puts the whole T on a 3D map of Boston:
- Every train, live. Vehicles, alerts and predictions come from the MBTA V3 API and move on a 3D city.
- Tap a stop for the next trains, the real gaps between them, and one-tap rider reports (on time, ghost train, packed).
- Street view. At eight stations you can fly down into a hand-drawn diorama of the actual block, in Boston's live weather.
- Fix the T. When a line stops, AI explains in plain English what broke. Then you walk into the tunnel and do the crew's job in a short 3D repair game (signal relays, rail welds, switches, power), and watch the crew finish.
- Ride your trip. Plan a trip and your avatar walks to the platform, rides, transfers and walks out, all in 3D.
I owned the 3D map: the Mapbox setup, the three.js layer that draws trains, stations and the avatar, and the trip ride. My teammates built the repair games, the HUD, the backend and rider features, and a hardware desk bot that ended up in the same submission.
The stack: Next.js 16, React 19, TypeScript and Tailwind 4 on the front end; Mapbox GL JS v3 with the Standard style (MapLibre GL as a fallback); three.js for everything we draw ourselves; Blender for eight station models; and a Python FastAPI backend that polls the MBTA once and serves everyone.
Demo
The bug: Boston's buildings ate our trains
Mapbox's Standard style gives you beautiful 3D buildings and lighting for free. On top of it, we render our own world with three.js through a Mapbox custom layer: trains, Blender station models, the rider avatar, the trip car.
The custom layer runs with renderingMode: "3d" and draws straight into Mapbox's own WebGL context:
// three.js draws into Mapbox's canvas and WebGL context, so it shares
// the depth buffer Mapbox just filled with 3D buildings.
this.renderer = new THREE.WebGLRenderer({ canvas: map.getCanvas(), context: gl, antialias: true });
this.renderer.autoClear = false;
Sharing the depth buffer is what makes our trains sit in the city instead of floating on top of it. It's also what broke us. Zoom out and everything looks great. Zoom in to street level, which is where the app is most fun, and the depth test does exactly its job: a 20-story building in front of the Red Line hides the Red Line. Lines, trains, station models and your planned trip all disappeared behind downtown.
A transit map that hides the transit isn't much of a map. We didn't want to turn the buildings off either, because the city is the point. So we fixed it in two parts.
Part 1: let the lines show through (Mapbox occlusion opacity)
Mapbox Standard has slots that decide where your layers sit in its draw order, and v3 line and symbol layers have an occlusion opacity: how much of the layer still shows when a 3D building is in front of it. We put our lines in the middle slot (above roads) and our stop names in top, then tuned the occlusion per layer:
/** How much of each line shows through a 3D building that hides it (0 hides it, 1 shows it all). */
const LINE_OCCLUSION: Record<string, number> = {
"rail-glow": 0.35, // the soft halo: keep it faint so it doesn't smear across buildings
"rail-core": 0.75, // the line itself
"rail-hot": 0.6,
"ride-core": 1, // your planned trip never disappears
"curb-path": 0.85, // the walk to a shuttle stop
};
for (const layer of [...transit, ...flatTransit, stationNames]) {
const slot = layer.type === "line" ? "middle" : "top";
const paint = { ...layer.paint };
if (layer.type === "line") paint["line-occlusion-opacity"] = LINE_OCCLUSION[layer.id] ?? 0.6;
if (layer.type === "symbol") Object.assign(paint, { "icon-occlusion-opacity": 0.85, "text-occlusion-opacity": 0.85 });
map.addLayer({ ...layer, slot, paint });
}
One value for everything didn't work. The soft halos need to stay faint behind buildings or they smear across the skyline, while your own planned route should never fade at all. So each layer gets its own number, tuned by eye on downtown Boston.
Part 2: an x-ray pass for our 3D models
Occlusion opacity only exists for Mapbox's own layers. Our trains and stations are three.js meshes, so we needed our own trick. It turned out to be one extra draw with a flipped depth test.
The idea: before we draw our scene normally, the depth buffer holds only Mapbox's city. If we draw a see-through "ghost" of each mesh with depthFunc: GreaterDepth, a pixel only passes where something is already closer to the camera than our mesh. That something is a building. Where nothing is in front, the ground is behind the train, so the test fails and no ghost appears.
Each real material gets a cached ghost twin (trimmed from our ThreeOverlayLayer.ts):
/** A flat, see-through twin of a solid material that only draws where a basemap building is in front. */
private xrayOf(src: THREE.Material): THREE.Material {
const cached = this.xrayMats.get(src); // WeakMap: one ghost per real material
if (cached) return cached;
let ghost: THREE.Material = this.xrayHidden; // glows and halos get no ghost
const glow = src.blending !== THREE.NormalBlending || (src.transparent && src.opacity < 0.6);
if (src.visible && src.depthTest && !glow) {
const m = src as THREE.MeshStandardMaterial;
ghost = new THREE.MeshBasicMaterial({
color: m.color?.clone() ?? new THREE.Color("#ffffff"),
map: m.map ?? null,
transparent: true,
opacity: 0.42,
depthWrite: false, // don't disturb the solid pass that follows
depthFunc: THREE.GreaterDepth, // draw ONLY where something is closer: a building
});
}
this.xrayMats.set(src, ghost);
return ghost;
}
And every frame, the custom layer's render() does two passes:
render(gl, args) {
// ...sync the three.js camera with Mapbox, move trains, animate the avatar...
this.renderer.resetState();
if (this.zoom >= XRAY_MIN_ZOOM) this.renderXray(now); // 1. ghosts, only behind buildings
this.renderer.render(this.scene, this.camera); // 2. the normal, solid scene
this.map.triggerRepaint();
}
private renderXray(now: number) {
// Every 0.5 s (not every frame), re-tag the meshes that have a ghost onto their own three.js layer.
if (now - this.xrayScanAt > 0.5) this.rescanXrayMeshes(now);
this.xrayMeshes.forEach((mesh, i) => { this.xraySolid[i] = mesh.material; mesh.material = this.xrayOf(mesh.material); });
this.camera.layers.set(XRAY_LAYER);
this.renderer.render(this.scene, this.camera);
this.camera.layers.set(0);
this.xrayMeshes.forEach((mesh, i) => { mesh.material = this.xraySolid[i]; }); // swap the real materials back
}
A few details that made it look right instead of glitchy:
- Ghosts use the model's own colours. A Red Line train ghosts red and a Green Line car ghosts green, so you can still read the map through a building. Lit parts use their emissive colour.
- Glows get no ghost. Additive or very transparent materials (halos, light beams) blow out into white smears when they double up behind buildings.
-
depthWrite: falseon the ghosts, so the solid pass afterwards still depth-tests against the city, not against our own ghosts. - Only when zoomed in (zoom 14.6 and closer). From the overview, buildings barely hide anything, so we skip the extra draw.
- It works on both engines. The x-ray pass is pure three.js, so it also runs on our MapLibre fallback, which has no occlusion opacity.
The whole fix was 69 lines across two files. It landed at 4:37 AM, about five hours before judging, and it's the reason the zoomed-in shots in our demo video show trains at all.
What I learned
- Shared depth is a feature, not just a constraint. Once three.js and Mapbox share a depth buffer, "draw only behind buildings" becomes one depth function instead of a raycasting system.
- Draw order is design. Mapbox's slots and our two passes are what decide what a rider sees first.
- Tune per layer, by eye. No single opacity works for halos, lines and your own route.
Partner Technologies
We used the Google Gemini API (via the google-genai Python SDK) for every piece of AI text in the app:
- The delay card. When a line stops, Gemini turns the raw MBTA alert into two sentences: what physically broke and why the wait is about N minutes, then the single smartest alternate move.
- The line pulse. One sentence on how a line feels right now, from its last five rider posts and the last 20 minutes of one-tap reports.
- The Tourist narrator. A short spoken blurb about what's above ground at a stop.
The model is gemini-3.5-flash-lite, which is fast enough for a rider standing on a platform. The system prompt keeps it honest:
_ALERT_SYSTEM = (
"You translate MBTA service alerts into plain English for riders standing on the platform. "
"Write exactly 2 sentences, under 65 words total, no markdown, no emojis, no lists. "
"Sentence 1: what physically broke or is being worked on, and why that makes the wait about the given number of minutes. "
"Sentence 2: the single smartest alternate move. "
"Stay factual: do not invent stations, routes, causes or numbers that are not in the input."
)
When a real alert doesn't match one of our repair scenarios, we don't feed the model our scenario notes at all. We tell it the cause isn't stated, so it can't make one up.
The rule we followed for a live demo: never block on the AI. Every card renders a written template first and upgrades to Gemini's text only if it arrives within 4 seconds. Answers are cached per alert for 10 minutes, so a hundred riders looking at the same delay cost one call.
One gotcha cost us real time. We first passed our 4-second budget as the SDK's HTTP timeout, and every call failed with 400 INVALID_ARGUMENT: Gemini rejects request deadlines under 10 seconds. The fix is to give the SDK a legal deadline and enforce our own budget with asyncio.wait_for:
# Gemini rejects request deadlines under 10 s; our own 4 s cap is the asyncio.wait_for around the call.
_client = genai.Client(api_key=key, http_options=genai_types.HttpOptions(timeout=10_000))
resp = await asyncio.wait_for(
client.aio.models.generate_content(
model=gemini_model(), # "gemini-3.5-flash-lite" unless GEMINI_MODEL overrides it
contents=prompt,
config=types.GenerateContentConfig(system_instruction=system, temperature=0.6, max_output_tokens=max_tokens),
),
timeout=max(0.1, _timeout_s() - (time.monotonic() - started)), # the 4 s budget includes client setup
)
Any timeout, quota error or empty answer falls back to the template, so the demo never froze on stage.
Hackathon Experience
BostonHacks 2026 went fast: 200+ commits in about 20 hours, split almost evenly between me and Videep.
I built it with Videep Singhal, Kirpa Gandhok and Atharv Gulati. Videep built the repair games and the HUD while I built the 3D map. With four people building into one screen, we split the code by folder and agreed on a shared data contract at the start, and that's the only reason the overnight merges worked.
The funniest problem was that the T sleeps. Service stops around 1 AM, which is exactly when we were testing. So we built a clearly labeled sample service that runs on the real tracks overnight and hands back to live trains at 6 AM. We recorded the final demo video right after 6, with 61 real trains on the map.
And the event itself was amazing. BU even provided sleeping mattresses for hackers, which I hadn't seen anywhere before, not even at HackPrinceton. The food was amazing too, and there were great activities going on throughout, even if I was too deep in depth buffers to join any. You can feel how much care BU puts into its hackathons. The mentors and organizers were amazing all weekend, and they're a big part of why we could ship this much in one night.
If you ride the T, I'd love to hear what you'd want from a map like this. And if you've fought a depth buffer to keep something visible behind 3D buildings, tell me how you did it in the comments.
來源:DEV Community · dev.to

