Spaces:
Running
Running
Download app.js from Rootkit29/spacenet-speedrun-map: direct link, hf CLI and curl.
- Browser
- Download file 33.3 kB
-
https://huggingface.co/spaces/Rootkit29/spacenet-speedrun-map/resolve/main/app.js
- Command line
-
hf download hf://spaces/Rootkit29/spacenet-speedrun-map/app.js
-
curl -L -o app.js https://huggingface.co/spaces/Rootkit29/spacenet-speedrun-map/resolve/main/app.js
33.3 kB
| /* global deck, maplibregl, pmtiles, basemaps */ | |
| // SpaceNet Speedrun cloud-native map. Every byte comes from static files (a Hugging Face dataset): | |
| // * basemap: one PMTiles archive (vector tiles), fonts and sprites; | |
| // * imagery: Cloud-Optimized GeoTIFFs (WebP tiles, Web Mercator), read tile by tile; | |
| // * vectors: GeoParquet 1.1 files, read row group by row group using the bbox statistics in their footers. | |
| // There is no tile server or database: the browser computes which byte ranges it needs and asks for them. | |
| import { stats, fetchJSON, RangeSource, ingest } from './hf.js'; | |
| import { COG } from './cog.js'; | |
| const HALF = 20037508.342789244; | |
| const params = new URLSearchParams(location.search); | |
| const DATA = (params.get('data') || | |
| 'https://huggingface.co/datasets/Rootkit29/spacenet-speedrun-map-data/resolve/main').replace(/\/$/, ''); | |
| const url = (p) => `${DATA}/${p.split('/').map(encodeURIComponent).join('/')}`; | |
| const toMerc = (lon, lat) => [lon * HALF / 180, Math.log(Math.tan((90 + lat) * Math.PI / 360)) * HALF / Math.PI]; | |
| const toLngLat = (x, y) => [x / HALF * 180, Math.atan(Math.exp(y / HALF * Math.PI)) * 360 / Math.PI - 90]; | |
| const fmtBytes = (b) => (b >= 1e9 ? `${(b / 1e9).toFixed(2)} GB` : b >= 1e6 ? `${(b / 1e6).toFixed(1)} MB` | |
| : b >= 1e3 ? `${(b / 1e3).toFixed(0)} KB` : `${b} B`); | |
| const fmtN = (n) => n.toLocaleString('en-US'); | |
| const hex = (h, a = 255) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16), a]; | |
| // ------------------------------------------------------------------------------------------------ layer styles | |
| const SPLIT = { train: '#5b9cf6', tune: '#a78bfa', val: '#fb923c', test: '#fb923c', 'train / tune': '#5b9cf6', | |
| 'official test (unlabelled)': '#94a3b8' }; | |
| const ROAD_TYPE = { motorway: '#f8fafc', primary: '#e2e8f0', secondary: '#cbd5e1', tertiary: '#94a3b8' }; | |
| const OV_SOURCE = { OpenStreetMap: '#7aa2ff', 'Microsoft ML Buildings': '#c084fc', 'Google Open Buildings': '#34d399', | |
| 'Esri Community Maps': '#fbbf24' }; | |
| const PLACE = { food_and_drink: '#f97316', shopping: '#ec4899', services_and_business: '#a3a3a3', | |
| health_care: '#ef4444', education: '#22d3ee', arts_and_entertainment: '#c084fc', lodging: '#facc15', | |
| travel_and_transportation: '#60a5fa', sports_and_recreation: '#4ade80', community_and_government: '#2dd4bf' }; | |
| const placeColor = (a) => hex(PLACE[a.category_group] ?? '#d4d4d8', 230); | |
| const LAYERS = [ | |
| { id: 'imagery', group: 'Imagery', label: 'WorldView-3 0.3 m', sub: 'Cloud-Optimized GeoTIFF', swatch: 'linear-gradient(135deg,#7c6f57,#c8b99a)', on: true }, | |
| { id: 'buildings_model', group: 'Model output', label: 'Model buildings', sub: 'whole Vegas strip + val chips', kind: 'polygon', minzoom: 14, on: true, maxGroups: 20, | |
| cols: ['city', 'product', 'confidence', 'area_m2', 'spacenet_split', 'model'], swatch: '#ffc400', | |
| fill: (a) => [255, 196, 0, 20 + Math.round(70 * Math.max(0, (a.confidence ?? 0.7) - 0.4) / 0.6)], line: () => [255, 196, 0, 230] }, | |
| { id: 'roads_model', group: 'Model output', label: 'Model roads', sub: 'whole Vegas strip (3,998 km) + test tiles', kind: 'line', minzoom: 11.5, on: true, | |
| cols: ['product', 'dataset', 'city', 'tile', 'tile_apls', 'length_m', 'model'], swatch: '#ff3d81', color: () => [255, 61, 129, 240], width: 3 }, | |
| { id: 'roads_model_main', group: 'Model output', label: 'Model main roads', sub: 'main-road output, whole Vegas strip', kind: 'line', minzoom: 11, on: false, | |
| cols: ['product', 'city', 'length_m', 'model'], swatch: '#ffd166', color: () => [255, 209, 102, 245], width: 5 }, | |
| { id: 'road_prob', group: 'Model output', label: 'Road probability', sub: '5-model ensemble, whole Vegas strip, 2.4 m', raster: true, on: false, | |
| swatch: 'linear-gradient(90deg,#78147a,#ff3d81,#fff5dc)' }, | |
| { id: 'buildings_spacenet', group: 'SpaceNet labels', label: 'Building labels', sub: 'SN2, 4 cities', kind: 'polygon', minzoom: 14, on: false, maxGroups: 20, | |
| cols: ['chip', 'city', 'split', 'area_m2'], swatch: '#22e3ff', fill: () => [34, 227, 255, 0], line: () => [34, 227, 255, 255], lineWidth: 1.5 }, | |
| { id: 'roads_spacenet', group: 'SpaceNet labels', label: 'Road labels', sub: 'SN3 + SN5, 6 cities', kind: 'line', minzoom: 11.5, on: false, | |
| cols: ['dataset', 'city', 'tile', 'split', 'road_type', 'lanes', 'paved', 'speed_mph'], swatch: '#4ade80', color: () => [74, 222, 128, 170], width: 4 }, | |
| { id: 'spacenet_tiles', group: 'SpaceNet labels', label: 'Tiles and splits', sub: 'SN2 chips, SN3 / SN5 tiles', kind: 'polygon', minzoom: 10, on: false, | |
| cols: ['dataset', 'tile', 'city', 'split'], swatch: '#5b9cf6', fill: (a) => hex(SPLIT[a.split] ?? '#94a3b8', 28), | |
| line: (a) => hex(SPLIT[a.split] ?? '#94a3b8', 200), lineWidth: 1 }, | |
| { id: 'overture_buildings', group: 'Overture Maps', label: 'Buildings', sub: 'height, floors, source', kind: 'polygon', minzoom: 15, on: false, maxGroups: 14, | |
| cols: ['city', 'name', 'class', 'height', 'num_floors', 'source'], swatch: '#7aa2ff', extrudable: true, | |
| fill: (a) => hex(OV_SOURCE[a.source] ?? '#a1a1aa', 70), line: (a) => hex(OV_SOURCE[a.source] ?? '#a1a1aa', 200) }, | |
| { id: 'overture_roads', group: 'Overture Maps', label: 'Roads and rail', sub: 'transportation segments', kind: 'line', minzoom: 13, on: false, | |
| cols: ['city', 'subtype', 'class', 'name', 'surface', 'source'], swatch: '#e2e8f0', | |
| color: (a) => (a.subtype === 'rail' ? [251, 191, 36, 200] : hex(ROAD_TYPE[a.class] ?? '#64748b', 210)), width: 2 }, | |
| { id: 'overture_places', group: 'Overture Maps', label: 'Places (POIs)', sub: 'confidence ≥ 0.5', kind: 'point', minzoom: 14, on: true, | |
| cols: ['city', 'name', 'category', 'category_group', 'confidence', 'website', 'source'], swatch: '#f97316', color: placeColor }, | |
| ]; | |
| const LEGEND = { | |
| buildings_model: [['fill opacity = model confidence', '#ffc400']], | |
| spacenet_tiles: [['train', SPLIT.train], ['tune', SPLIT.tune], ['val / test', SPLIT.val], ['official test', SPLIT['official test (unlabelled)']]], | |
| overture_buildings: [['OSM', OV_SOURCE.OpenStreetMap], ['Microsoft', OV_SOURCE['Microsoft ML Buildings']], | |
| ['Google', OV_SOURCE['Google Open Buildings']], ['Esri', OV_SOURCE['Esri Community Maps']], ['other', '#a1a1aa']], | |
| overture_roads: [['major road', '#e2e8f0'], ['minor road', '#64748b'], ['rail', '#fbbf24']], | |
| overture_places: [['food', PLACE.food_and_drink], ['shopping', PLACE.shopping], ['health', PLACE.health_care], | |
| ['education', PLACE.education], ['lodging', PLACE.lodging], ['transport', PLACE.travel_and_transportation], | |
| ['recreation', PLACE.sports_and_recreation], ['other', '#d4d4d8']], | |
| }; | |
| const DEF = Object.fromEntries(LAYERS.map((d) => [d.id, d])); | |
| for (const d of LAYERS) d.on = params.has(d.id) ? params.get(d.id) !== '0' : d.on; | |
| const OPEN_ZOOM = 9; // below this, nothing but the basemap is read | |
| const TEX = { minFilter: 'linear', magFilter: 'linear' }; | |
| const MATERIAL = { ambient: 0.45, diffuse: 0.6, shininess: 20 }; | |
| const ui = { xray: params.get('xray') === '1', extrude: false }; | |
| let map; | |
| let overlay; | |
| let beforeId; | |
| let manifest; | |
| let imagery; | |
| const rasters = {}; // extra COG layers (model outputs), by layer id | |
| const sources = {}; | |
| const layerMeta = new Map(); // deck layer id -> { def, batch } | |
| // ------------------------------------------------------------------------------------------------ redraw | |
| let redrawQueued = false; | |
| function redraw() { | |
| if (redrawQueued) return; | |
| redrawQueued = true; | |
| requestAnimationFrame(() => { | |
| redrawQueued = false; | |
| overlay?.setProps({ layers: buildLayers() }); | |
| renderLayerStatus(); | |
| clearTimeout(countTimer); | |
| countTimer = setTimeout(() => map && countInView(currentView()), 400); | |
| }); | |
| } | |
| let countTimer = 0; | |
| function currentView() { | |
| const b = map.getBounds(); | |
| const c = map.getCenter(); | |
| return { bbox: [b.getWest(), b.getSouth(), b.getEast(), b.getNorth()], zoom: map.getZoom(), center: [c.lng, c.lat] }; | |
| } | |
| let updateTimer = 0; | |
| function scheduleUpdate(now = false) { | |
| clearTimeout(updateTimer); | |
| updateTimer = setTimeout(() => { | |
| const v = currentView(); | |
| imagery?.update(v); | |
| for (const r of Object.values(rasters)) r.update(v); | |
| for (const s of Object.values(sources)) s.update(v); | |
| redraw(); | |
| countInView(v); | |
| }, now ? 0 : 120); | |
| } | |
| // ------------------------------------------------------------------------------------------------ imagery (COG) | |
| class Imagery { | |
| constructor(items, id = 'imagery') { | |
| this.id = id; | |
| this.items = items.map((it) => ({ ...it, merc: [...toMerc(it.bounds[0], it.bounds[1]), ...toMerc(it.bounds[2], it.bounds[3])] })); | |
| this.cache = new Map(); // key -> { bmp, bounds, merc, res, t } | |
| this.pending = new Map(); // key -> AbortController | |
| this.levelNow = {}; | |
| this.stats = { tiles: 0 }; | |
| } | |
| update(v) { | |
| if (!DEF[this.id].on) { | |
| for (const ac of this.pending.values()) ac.abort(); | |
| this.pending.clear(); | |
| return; | |
| } | |
| const [x0, y0] = toMerc(v.bbox[0], v.bbox[1]); | |
| const [x1, y1] = toMerc(v.bbox[2], v.bbox[3]); | |
| this.view = [x0, y0, x1, y1]; | |
| const dpr = Math.min(window.devicePixelRatio || 1, 2); | |
| const mpp = (2 * HALF) / (512 * 2 ** v.zoom) / (dpr > 1 ? 1.4 : 1); | |
| const need = new Set(); | |
| for (const it of this.items) { | |
| const m = it.merc; | |
| if (m[0] > x1 || m[2] < x0 || m[1] > y1 || m[3] < y0) continue; | |
| if (!it.cog) { | |
| if (v.zoom < OPEN_ZOOM) continue; | |
| it.opening ??= new COG(url(it.path), { size: it.size }).open().then((c) => { it.cog = c; scheduleUpdate(true); }) | |
| .catch((e) => console.warn('COG', it.path, e)); | |
| continue; | |
| } | |
| const c = it.cog; | |
| let lv = 0; | |
| c.levels.forEach((l, k) => { if (l.res <= mpp) lv = k; }); | |
| let range; | |
| for (;;) { | |
| const l = c.levels[lv]; | |
| const ax = Math.max(x0, c.bounds[0]); | |
| const bx = Math.min(x1, c.bounds[2]); | |
| const ay = Math.max(y0, c.bounds[1]); | |
| const by = Math.min(y1, c.bounds[3]); | |
| range = [Math.floor((ax - c.originX) / (l.tw * l.res)), Math.floor((bx - c.originX) / (l.tw * l.res) - 1e-9), | |
| Math.floor((c.originY - by) / (l.th * l.resY)), Math.floor((c.originY - ay) / (l.th * l.resY) - 1e-9)]; | |
| if ((range[1] - range[0] + 1) * (range[3] - range[2] + 1) <= 64 || lv === c.levels.length - 1) break; | |
| lv += 1; | |
| } | |
| this.levelNow[it.path] = c.levels[lv].res; | |
| for (let col = range[0]; col <= range[1]; col++) { | |
| for (let row = range[2]; row <= range[3]; row++) { | |
| const key = `${it.path}|${lv}|${col}|${row}`; | |
| need.add(key); | |
| const hit = this.cache.get(key); | |
| if (hit) { hit.t = performance.now(); continue; } | |
| if (this.pending.has(key)) continue; | |
| const ac = new AbortController(); | |
| this.pending.set(key, ac); | |
| const tb = c.tileBounds(lv, col, row); | |
| c.tile(lv, col, row, ac.signal).then((bmp) => { | |
| const [w, s] = toLngLat(tb[0], tb[1]); | |
| const [e, n] = toLngLat(tb[2], tb[3]); | |
| this.cache.set(key, { key, bmp, bounds: [w, s, e, n], merc: tb, res: c.levels[lv].res, path: it.path, t: performance.now() }); | |
| if (bmp) this.stats.tiles += 1; | |
| this.evict(); | |
| redraw(); | |
| }).catch((e) => { if (e.name !== 'AbortError') console.warn(e); }) | |
| .finally(() => this.pending.delete(key)); | |
| } | |
| } | |
| } | |
| for (const [k, ac] of this.pending) if (!need.has(k)) { ac.abort(); this.pending.delete(k); } | |
| this.need = need; | |
| } | |
| evict() { | |
| if (this.cache.size <= 220) return; | |
| const old = [...this.cache.values()].filter((t) => !this.need?.has(t.key)).sort((a, b) => a.t - b.t); | |
| for (const t of old.slice(0, this.cache.size - 220)) { | |
| t.bmp?.close?.(); | |
| this.cache.delete(t.key); | |
| } | |
| } | |
| layers() { | |
| if (!DEF[this.id].on || !this.view) return []; | |
| const [x0, y0, x1, y1] = this.view; | |
| const vis = [...this.cache.values()].filter((t) => t.bmp && t.merc[0] < x1 && t.merc[2] > x0 && t.merc[1] < y1 && t.merc[3] > y0 | |
| && t.res >= (this.levelNow[t.path] ?? 0) / 2.01); | |
| vis.sort((a, b) => b.res - a.res); // coarse first, sharper tiles drawn on top | |
| return vis.map((t) => new deck.BitmapLayer({ id: `${this.id}-${t.key}`, image: t.bmp, bounds: t.bounds, beforeId, | |
| textureParameters: TEX })); | |
| } | |
| xray() { | |
| const cells = [...this.cache.values()].filter((t) => this.need?.has(t.key)); | |
| return new deck.PolygonLayer({ id: `xray-cog-${this.id}`, data: cells, beforeId, filled: false, stroked: true, | |
| getPolygon: (t) => [[t.bounds[0], t.bounds[1]], [t.bounds[2], t.bounds[1]], [t.bounds[2], t.bounds[3]], [t.bounds[0], t.bounds[3]]], | |
| getLineColor: (t) => (t.bmp ? [255, 255, 255, 150] : [255, 255, 255, 40]), lineWidthUnits: 'pixels', getLineWidth: 1 }); | |
| } | |
| } | |
| // ------------------------------------------------------------------------------------------------ vectors (GeoParquet) | |
| // Parquet reading and decoding run in a small pool of module workers; the page only builds deck.gl layers. | |
| const workers = Array.from({ length: Math.min(4, Math.max(2, (navigator.hardwareConcurrency || 4) - 2)) }, () => { | |
| const w = new Worker(new URL('./pqworker.js', import.meta.url), { type: 'module' }); | |
| w.onmessage = ({ data: m }) => { | |
| if (m.type === 'stat') { if (m.entry) ingest(m.entry); return; } | |
| const p = calls.get(m.id); | |
| calls.delete(m.id); | |
| if (m.error) p.reject(new Error(m.error)); else p.resolve(m.result); | |
| }; | |
| return w; | |
| }); | |
| const calls = new Map(); | |
| let callId = 0; | |
| function call(w, msg) { | |
| const id = ++callId; | |
| return new Promise((resolve, reject) => { calls.set(id, { resolve, reject }); w.postMessage({ ...msg, id }); }); | |
| } | |
| /** Same interface as GeoParquet, backed by the worker pool. Each file's footer is read once per worker. */ | |
| class RemoteGeoParquet { | |
| constructor(path, size, footer) { | |
| this.msg = { url: url(path), size, footer }; | |
| this.seen = new Set([0]); | |
| } | |
| async open() { | |
| Object.assign(this, await call(workers[0], { ...this.msg, op: 'open' })); | |
| return this; | |
| } | |
| read(i, cols) { | |
| const k = i % workers.length; | |
| const first = !this.seen.has(k); | |
| this.seen.add(k); | |
| return call(workers[k], { ...this.msg, op: 'read', i, cols, tail: first ? this.tail : undefined }); | |
| } | |
| } | |
| class VectorSource { | |
| constructor(def, info) { | |
| this.def = def; | |
| this.info = info; | |
| this.loaded = new Map(); // row group -> batch | |
| this.loading = new Set(); | |
| this.queue = []; | |
| this.active = 0; | |
| this.visible = new Set(); | |
| this.status = ''; | |
| } | |
| async ensureOpen() { | |
| this.opening ??= new RemoteGeoParquet(this.info.path, this.info.size, this.info.footer).open().then((pq) => { | |
| this.pq = pq; | |
| scheduleUpdate(true); | |
| }).catch((e) => { this.status = `error: ${e.message}`; console.warn(e); }); | |
| return this.opening; | |
| } | |
| update(v) { | |
| if (!this.def.on) { this.visible = new Set(); this.queue = []; this.status = ''; return; } | |
| if (!this.pq) { | |
| if (v.zoom < OPEN_ZOOM) { this.status = `zoom in to ${this.def.minzoom}+ to stream`; this.zoomBlocked = true; return; } | |
| this.ensureOpen(); | |
| this.status = 'reading footer…'; | |
| return; | |
| } | |
| const [x0, y0, x1, y1] = v.bbox; | |
| this.view = v.bbox; | |
| if (v.zoom < this.def.minzoom) { | |
| this.visible = new Set(); | |
| this.queue = []; | |
| const hits = this.pq.rowGroups.filter((g) => g.bbox[0] <= x1 && g.bbox[2] >= x0 && g.bbox[1] <= y1 && g.bbox[3] >= y0); | |
| this.status = hits.length ? `zoom in to ${this.def.minzoom}+ to stream (${hits.length} row groups here)` : 'nothing here'; | |
| this.zoomBlocked = true; | |
| return; | |
| } | |
| this.zoomBlocked = false; | |
| const [cx, cy] = v.center; | |
| const dist = (g) => Math.hypot((g.bbox[0] + g.bbox[2]) / 2 - cx, (g.bbox[1] + g.bbox[3]) / 2 - cy); | |
| const hits = this.pq.rowGroups.filter((g) => g.bbox[0] <= x1 && g.bbox[2] >= x0 && g.bbox[1] <= y1 && g.bbox[3] >= y0) | |
| .sort((a, b) => dist(a) - dist(b)); | |
| const take = hits.slice(0, this.def.maxGroups ?? 40); | |
| this.partial = hits.length - take.length; | |
| this.visible = new Set(take.map((g) => g.i)); | |
| this.queue = take.filter((g) => !this.loaded.has(g.i) && !this.loading.has(g.i)); | |
| this.pump(); | |
| this.evict(dist); | |
| } | |
| pump() { | |
| while (this.active < 3 && this.queue.length) { | |
| const g = this.queue.shift(); | |
| if (!this.visible.has(g.i) || this.loaded.has(g.i) || this.loading.has(g.i)) continue; | |
| this.active += 1; | |
| this.loading.add(g.i); | |
| this.pq.read(g.i, this.def.cols).then((batch) => { | |
| batch.group = g; | |
| this.loaded.set(g.i, batch); | |
| }).catch((e) => console.warn(this.def.id, g.i, e)).finally(() => { | |
| this.active -= 1; | |
| this.loading.delete(g.i); | |
| this.pump(); | |
| redraw(); | |
| }); | |
| } | |
| } | |
| evict(dist) { | |
| const budget = this.def.maxRows ?? 200_000; | |
| let rows = 0; | |
| for (const b of this.loaded.values()) rows += b.n; | |
| if (rows <= budget) return; | |
| const far = [...this.loaded.values()].filter((b) => !this.visible.has(b.group.i)).sort((a, b) => dist(b.group) - dist(a.group)); | |
| for (const b of far) { | |
| if (rows <= budget) break; | |
| rows -= b.n; | |
| this.loaded.delete(b.group.i); | |
| } | |
| } | |
| layers() { | |
| if (!this.def.on || this.zoomBlocked) return []; | |
| const d = this.def; | |
| const out = []; | |
| for (const [i, b] of this.loaded) { | |
| if (!this.visible.has(i)) continue; | |
| const id = `${d.id}-${i}`; | |
| layerMeta.set(id, { def: d, batch: b }); | |
| const A = b.attrs; | |
| if (d.kind === 'polygon' && b.polys) { | |
| const ext = d.extrudable && ui.extrude; | |
| out.push(new deck.PolygonLayer({ | |
| id, data: b.polys, beforeId, pickable: true, positionFormat: 'XY', getPolygon: (p) => p.polygon, | |
| filled: true, stroked: !ext, extruded: ext, wireframe: false, | |
| getElevation: (p) => A[p.f].height ?? (A[p.f].num_floors ? A[p.f].num_floors * 3.2 : 4), | |
| getFillColor: (p) => d.fill(A[p.f]), getLineColor: (p) => d.line(A[p.f]), | |
| lineWidthUnits: 'pixels', getLineWidth: d.lineWidth ?? 1, autoHighlight: true, highlightColor: [255, 255, 255, 90], | |
| material: ext ? MATERIAL : false, | |
| updateTriggers: { getFillColor: ext, getElevation: ext }, | |
| })); | |
| } else if (d.kind === 'line' && b.paths) { | |
| out.push(new deck.PathLayer({ | |
| id, data: b.paths, beforeId, pickable: true, positionFormat: 'XY', getPath: (p) => p.path, | |
| getColor: (p) => d.color(A[p.f]), widthUnits: 'meters', getWidth: d.width ?? 3, widthMinPixels: 1.5, | |
| capRounded: true, jointRounded: true, autoHighlight: true, highlightColor: [255, 255, 255, 160], | |
| })); | |
| } else if (d.kind === 'point' && b.points) { | |
| b.pointObjs ??= Array.from(b.pointFeature, (f, k) => ({ p: [b.points[2 * k], b.points[2 * k + 1]], f })); | |
| out.push(new deck.ScatterplotLayer({ | |
| id, data: b.pointObjs, beforeId, pickable: true, getPosition: (p) => p.p, getFillColor: (p) => d.color(A[p.f]), | |
| radiusUnits: 'pixels', getRadius: 4, stroked: true, getLineColor: [10, 10, 14, 220], lineWidthUnits: 'pixels', | |
| getLineWidth: 1, autoHighlight: true, highlightColor: [255, 255, 255, 220], | |
| })); | |
| } | |
| } | |
| return out; | |
| } | |
| xray() { | |
| if (!this.def.on || !this.pq) return []; | |
| const groups = this.pq.rowGroups; | |
| const col = hex(typeof this.def.swatch === 'string' && this.def.swatch.startsWith('#') ? this.def.swatch : '#ffffff'); | |
| const live = groups.filter((g) => this.loaded.has(g.i) && this.visible.has(g.i)); | |
| const key = [this.loaded.size, this.visible.size]; | |
| return [ | |
| new deck.PolygonLayer({ | |
| id: `xray-${this.def.id}`, data: groups, beforeId, pickable: true, | |
| getPolygon: (g) => [[g.bbox[0], g.bbox[1]], [g.bbox[2], g.bbox[1]], [g.bbox[2], g.bbox[3]], [g.bbox[0], g.bbox[3]]], | |
| filled: true, stroked: true, lineWidthUnits: 'pixels', | |
| getLineWidth: (g) => (this.loaded.has(g.i) ? 2 : 1), | |
| getFillColor: (g) => (this.loaded.has(g.i) && this.visible.has(g.i) ? [...col.slice(0, 3), 14] : [0, 0, 0, 0]), | |
| getLineColor: (g) => [...col.slice(0, 3), this.loaded.has(g.i) ? 255 : 90], | |
| updateTriggers: { getFillColor: key, getLineColor: key, getLineWidth: key }, | |
| }), | |
| new deck.TextLayer({ | |
| id: `xray-t-${this.def.id}`, data: live, getPosition: (g) => [g.bbox[0], g.bbox[3]], | |
| getText: (g) => `${this.def.id} · rg ${g.i} · ${fmtN(g.rows)} rows · ${fmtBytes(g.bytes)}`, | |
| getSize: 11, getColor: [...col.slice(0, 3), 255], background: true, getBackgroundColor: [10, 12, 18, 220], | |
| backgroundPadding: [4, 2], getTextAnchor: 'start', getAlignmentBaseline: 'top', fontFamily: 'JetBrains Mono, monospace', | |
| characterSet: 'auto', updateTriggers: { getText: key }, | |
| }), | |
| ]; | |
| } | |
| } | |
| function cityLayers() { | |
| if (!map || map.getZoom() >= 10 || !manifest) return []; | |
| const data = Object.entries(manifest.cities).map(([name, c]) => ({ name, ...c })); | |
| const fly = ({ object }) => object && map.flyTo({ center: object.focus, zoom: object.zoom, speed: 1.6 }); | |
| return [ | |
| new deck.ScatterplotLayer({ id: 'cities', data, getPosition: (c) => c.focus, radiusUnits: 'pixels', getRadius: 7, | |
| getFillColor: [255, 196, 0, 255], stroked: true, getLineColor: [11, 13, 18, 255], lineWidthUnits: 'pixels', getLineWidth: 2, | |
| pickable: true, onClick: fly }), | |
| new deck.TextLayer({ id: 'city-names', data, getPosition: (c) => c.focus, getText: (c) => `${c.name} · ${c.note}`, | |
| getSize: 13, getColor: [255, 255, 255, 255], getPixelOffset: [12, 0], getTextAnchor: 'start', getAlignmentBaseline: 'center', | |
| background: true, getBackgroundColor: [11, 13, 18, 210], backgroundPadding: [6, 3], fontFamily: 'Inter, sans-serif', | |
| fontWeight: 600, pickable: true, onClick: fly }), | |
| ]; | |
| } | |
| function buildLayers() { | |
| const out = [...(imagery?.layers() ?? []), ...Object.values(rasters).flatMap((r) => r.layers())]; | |
| for (const id of ['spacenet_tiles', 'overture_buildings', 'buildings_spacenet', 'buildings_model', 'overture_roads', | |
| 'roads_spacenet', 'roads_model', 'roads_model_main', 'overture_places']) { | |
| if (sources[id]) out.push(...sources[id].layers()); | |
| } | |
| if (ui.xray) { | |
| if (DEF.imagery.on && imagery) out.push(imagery.xray()); | |
| for (const r of Object.values(rasters)) if (DEF[r.id].on) out.push(r.xray()); | |
| for (const s of Object.values(sources)) out.push(...s.xray()); | |
| } | |
| out.push(...cityLayers()); | |
| return out; | |
| } | |
| // ------------------------------------------------------------------------------------------------ in-view counts | |
| function countInView(v) { | |
| const [x0, y0, x1, y1] = v.bbox; | |
| const out = []; | |
| for (const id of ['buildings_model', 'buildings_spacenet', 'overture_buildings', 'roads_model', 'roads_spacenet', 'overture_places']) { | |
| const s = sources[id]; | |
| if (!s || !s.def.on || s.zoomBlocked) continue; | |
| let n = 0; | |
| for (const [i, b] of s.loaded) { | |
| if (!s.visible.has(i)) continue; | |
| const seen = new Uint8Array(b.n); | |
| const items = b.polys ?? b.paths; | |
| if (items) { | |
| for (const it of items) { | |
| const a = it.polygon?.positions ?? it.polygon ?? it.path; | |
| if (!seen[it.f] && a[0] >= x0 && a[0] <= x1 && a[1] >= y0 && a[1] <= y1) { seen[it.f] = 1; n += 1; } | |
| } | |
| } else if (b.points) { | |
| for (let k = 0; k < b.pointFeature.length; k++) { | |
| const x = b.points[2 * k]; | |
| const y = b.points[2 * k + 1]; | |
| if (x >= x0 && x <= x1 && y >= y0 && y <= y1) n += 1; | |
| } | |
| } | |
| } | |
| out.push(`<span><b>${fmtN(n)}</b> ${s.def.short ?? s.def.label.toLowerCase()}</span>`); | |
| } | |
| document.getElementById('inview').innerHTML = out.length ? `In view: ${out.join(' · ')}` : ''; | |
| } | |
| // ------------------------------------------------------------------------------------------------ tooltip | |
| const LABELS = { length_m: 'length m', area_m2: 'area m²', tile_apls: 'tile APLS', spacenet_split: 'SpaceNet split', num_floors: 'floors', | |
| category_group: 'group', speed_mph: 'speed (mph)', road_type: 'road type' }; | |
| function tooltip(info) { | |
| if (!info.layer || !info.object) return null; | |
| const id = info.layer.id; | |
| if (id === 'cities' || id === 'city-names') return { className: 'tip', html: `<div class="tip-h">${info.object.name}</div><div>Click to fly there</div>` }; | |
| if (id.startsWith('xray-')) { | |
| const g = info.object; | |
| if (g.rows === undefined) return null; | |
| const src = id.slice(5); | |
| return { className: 'tip', html: `<div class="tip-h">${DEF[src].label}: row group ${g.i}</div>` + | |
| `<div>${fmtN(g.rows)} rows · ${fmtBytes(g.bytes)}</div><div class="tip-m">${sources[src].loaded.has(g.i) ? 'fetched' : 'not fetched'}</div>` }; | |
| } | |
| const m = layerMeta.get(id); | |
| if (!m) return null; | |
| const a = m.batch.attrs[info.object.f]; | |
| const rows = Object.entries(a).filter(([, v]) => v !== null && v !== undefined && v !== '' && !(typeof v === 'number' && Number.isNaN(v))) | |
| .map(([k, v]) => `<tr><td>${LABELS[k] ?? k.replace(/_/g, ' ')}</td><td>${typeof v === 'number' ? (Number.isInteger(v) ? fmtN(v) : v.toFixed(3).replace(/\.?0+$/, '')) : String(v).replace(/</g, '<')}</td></tr>`) | |
| .join(''); | |
| return { className: 'tip', html: `<div class="tip-h">${m.def.label}</div><table>${rows}</table>` + | |
| `<div class="tip-m">row group ${m.batch.group.i} of ${sources[m.def.id].pq.rowGroups.length} in ${m.def.id}.parquet</div>` }; | |
| } | |
| // ------------------------------------------------------------------------------------------------ UI | |
| function renderLayerStatus() { | |
| for (const d of LAYERS) { | |
| const el = document.querySelector(`[data-status="${d.id}"]`); | |
| if (!el) continue; | |
| if (d.id === 'imagery' || d.raster) { | |
| const im = d.id === 'imagery' ? imagery : rasters[d.id]; | |
| el.textContent = d.on && im ? `${im.items.length} COG${im.items.length > 1 ? 's' : ''} · ${fmtN(im.stats.tiles)} tiles fetched` : ''; | |
| continue; | |
| } | |
| const s = sources[d.id]; | |
| if (!s || !d.on) { el.textContent = ''; continue; } | |
| if (!s.pq || s.zoomBlocked) { el.textContent = s.status; continue; } | |
| let rows = 0; | |
| for (const i of s.visible) rows += s.loaded.get(i)?.n ?? 0; | |
| const pend = s.loading.size + s.queue.length; | |
| el.textContent = `${s.visible.size} of ${s.pq.rowGroups.length} row groups · ${fmtN(rows)} rows` + | |
| (pend ? ` · loading ${pend}` : '') + (s.partial ? ` · ${s.partial} more: zoom in` : ''); | |
| } | |
| } | |
| function buildPanel() { | |
| const list = document.getElementById('layers'); | |
| let group = ''; | |
| for (const d of LAYERS) { | |
| const present = d.id === 'imagery' || (d.raster ? manifest.rasters?.[d.id] : manifest.vectors[d.id]); | |
| if (!present) continue; // e.g. a model layer not produced yet | |
| if (d.group !== group) { | |
| group = d.group; | |
| list.insertAdjacentHTML('beforeend', `<div class="grp">${group}</div>`); | |
| } | |
| const info = d.id === 'imagery' ? manifest.imagery.reduce((s, x) => s + x.size, 0) | |
| : d.raster ? manifest.rasters[d.id].reduce((s, x) => s + x.size, 0) : manifest.vectors[d.id]?.size; | |
| const rows = manifest.vectors[d.id]?.rows; | |
| list.insertAdjacentHTML('beforeend', ` | |
| <label class="lyr"> | |
| <input type="checkbox" data-layer="${d.id}" ${d.on ? 'checked' : ''}> | |
| <span class="sw" style="background:${d.swatch}"></span> | |
| <span class="lt"><span class="ln">${d.label}</span> | |
| <span class="ls">${d.sub}${rows ? ` · ${fmtN(rows)} rows` : ''}${info ? ` · ${fmtBytes(info)}` : ''}${d.raster ? ' · COG' : ''}</span> | |
| ${LEGEND[d.id] ? `<span class="lg">${LEGEND[d.id].map(([t, c]) => `<i style="--c:${c}">${t}</i>`).join('')}</span>` : ''} | |
| <span class="st" data-status="${d.id}"></span></span> | |
| ${d.extrudable ? '<button class="mini" id="extrude" title="Extrude by height">3D</button>' : ''} | |
| </label>`); | |
| } | |
| list.addEventListener('change', (e) => { | |
| const id = e.target.dataset.layer; | |
| if (!id) return; | |
| DEF[id].on = e.target.checked; | |
| if (DEF[id].on && sources[id]) sources[id].ensureOpen(); | |
| scheduleUpdate(true); | |
| }); | |
| document.getElementById('extrude')?.addEventListener('click', (e) => { | |
| e.preventDefault(); | |
| ui.extrude = !ui.extrude; | |
| e.target.classList.toggle('on', ui.extrude); | |
| if (ui.extrude) { | |
| DEF.overture_buildings.on = true; | |
| document.querySelector('[data-layer="overture_buildings"]').checked = true; | |
| if (map.getZoom() < 15.5) map.easeTo({ zoom: 16, pitch: 55, bearing: -20, duration: 1200 }); | |
| else map.easeTo({ pitch: 55, duration: 800 }); | |
| } else map.easeTo({ pitch: 0, bearing: 0, duration: 800 }); | |
| scheduleUpdate(true); | |
| }); | |
| const xr = document.getElementById('xray'); | |
| xr.classList.toggle('on', ui.xray); | |
| xr.addEventListener('click', () => { ui.xray = !ui.xray; xr.classList.toggle('on', ui.xray); redraw(); }); | |
| const cities = document.getElementById('cities'); | |
| for (const [name, c] of Object.entries(manifest.cities)) { | |
| const b = document.createElement('button'); | |
| b.className = 'city'; | |
| b.innerHTML = `${name}<small>${c.note}</small>`; | |
| b.onclick = () => map.flyTo({ center: c.focus, zoom: c.zoom, pitch: 0, bearing: 0, speed: 1.6 }); | |
| cities.appendChild(b); | |
| } | |
| document.getElementById('world').onclick = () => map.flyTo({ center: [10, 25], zoom: 1.3, pitch: 0, bearing: 0 }); | |
| document.getElementById('collapse').onclick = () => document.body.classList.toggle('collapsed'); | |
| const total = manifest.totals.bytes; | |
| document.getElementById('hosted').textContent = fmtBytes(total); | |
| document.getElementById('hosted-n').textContent = `${fmtN(manifest.totals.files)} files · ${fmtN(manifest.totals.features)} vector features · ${fmtN(Math.round(manifest.totals.gigapixels))} gigapixels`; | |
| } | |
| let hudQueued = false; | |
| function renderHud() { | |
| if (hudQueued) return; | |
| hudQueued = true; | |
| requestAnimationFrame(() => { | |
| hudQueued = false; | |
| const total = manifest?.totals.bytes ?? 1; | |
| document.getElementById('streamed').textContent = fmtBytes(stats.bytes); | |
| document.getElementById('pct').textContent = `${(100 * stats.bytes / total).toFixed(stats.bytes / total < 0.01 ? 3 : 2)}%`; | |
| document.getElementById('nreq').textContent = fmtN(stats.requests); | |
| const fm = { pmtiles: 'PMTiles basemap', cog: 'COG imagery', parquet: 'GeoParquet', json: 'manifest / style' }; | |
| document.getElementById('byfmt').innerHTML = Object.entries(stats.byFormat) | |
| .map(([k, v]) => `<div><span>${fm[k] ?? k}</span><span>${fmtN(v.requests)} req</span><span>${fmtBytes(v.bytes)}</span></div>`).join(''); | |
| document.getElementById('log').innerHTML = stats.log.slice(0, 7).map((r) => | |
| `<div><span class="f">${r.file}</span><span>${r.start.toLocaleString('en-US')}–${r.end.toLocaleString('en-US')}</span><span>${fmtBytes(r.bytes)}</span><span>${r.ms < 1000 ? `${r.ms} ms` : `${(r.ms / 1000).toFixed(1)} s`}</span></div>`).join(''); | |
| }); | |
| } | |
| // ------------------------------------------------------------------------------------------------ boot | |
| async function main() { | |
| stats.listeners.add(renderHud); | |
| manifest = await fetchJSON(url('manifest.json')); | |
| buildPanel(); | |
| const protocol = new pmtiles.Protocol(); | |
| maplibregl.addProtocol('pmtiles', protocol.tile); | |
| const src = new RangeSource(url(manifest.basemap.path)); | |
| protocol.add(new pmtiles.PMTiles(src)); | |
| const style = { | |
| version: 8, | |
| glyphs: `${DATA}/basemap/fonts/{fontstack}/{range}.pbf`, | |
| sprite: new URL(`${DATA}/basemap/sprites/dark`, location.href).href, | |
| sources: { protomaps: { type: 'vector', url: `pmtiles://${src.getKey()}`, | |
| attribution: '<a href="https://protomaps.com">Protomaps</a> © <a href="https://openstreetmap.org/copyright">OpenStreetMap</a>' } }, | |
| layers: basemaps.layers('protomaps', basemaps.namedFlavor('dark'), { lang: 'en' }), | |
| }; | |
| const start = manifest.cities[params.get('city')] ?? manifest.cities.Vegas; | |
| map = new maplibregl.Map({ | |
| container: 'map', style, center: start.focus, zoom: start.zoom, hash: 'view', maxPitch: 70, | |
| attributionControl: { compact: true, customAttribution: manifest.attribution }, | |
| }); | |
| map.addControl(new maplibregl.NavigationControl({ visualizePitch: true }), 'top-right'); | |
| map.addControl(new maplibregl.ScaleControl({ unit: 'metric' }), 'bottom-left'); | |
| map.on('load', () => { | |
| beforeId = map.getStyle().layers.find((l) => l.type === 'symbol')?.id; | |
| overlay = new deck.MapboxOverlay({ interleaved: true, layers: [], getTooltip: tooltip, pickingRadius: 5 }); | |
| map.addControl(overlay); | |
| imagery = new Imagery(manifest.imagery); | |
| for (const [id, items] of Object.entries(manifest.rasters ?? {})) if (DEF[id]) rasters[id] = new Imagery(items, id); | |
| for (const d of LAYERS) if (manifest.vectors[d.id]) sources[d.id] = new VectorSource(d, manifest.vectors[d.id]); | |
| scheduleUpdate(true); | |
| }); | |
| map.on('move', () => scheduleUpdate()); | |
| map.on('moveend', () => scheduleUpdate(true)); | |
| window.__map = { map, sources, stats, get imagery() { return imagery; }, get deck() { return overlay?._deck; } }; | |
| } | |
| main().catch((e) => { | |
| console.error(e); | |
| document.getElementById('err').textContent = `Could not start: ${e.message}`; | |
| }); | |