Files
BoucleduHainaut-ar/www/lidar.js
T
mathieuandClaude Opus 5.5 a00af81443 v47 : masquer une précision absente du site (ex. « Très précis » sur OVH)
Si data/lidar/<précision>/index.json renvoie 404, le choix disparaît des
réglages, d'Expert et de la fenêtre de téléchargement, et l'app revient à
« Moyen ». Permet de publier sans la précision 1 m (83 Mo) sur un
hébergement à place limitée.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 22:48:28 +01:00

180 lines
8.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Masquage par le relief LiDAR (SPW 2021-2022, + Flandre DHMV II) : bâtiments, arbres, haies…
// Chaque dalle de 1 km (data/lidar/{1m,2m,4m}/kx_ky.png) donne la hauteur au-dessus du sol
// (gris × 0,2 m, ligne 0 = nord). On en fait une surface invisible qui n'écrit que dans le tampon
// de profondeur, comme les bâtiments OSM : les pylônes et câbles situés derrière ne sont pas dessinés.
// Les hauteurs sont posées sur le relief du terrain (terrain.js) : y = altitude du sol + hauteur.
import * as THREE from 'three';
import { withClearZone } from './terrain.js?v=47';
const TILE = 1000; // m
export class LidarOccluders {
constructor({ scene, projection, terrain, baseUrl, radius = 800, onError = () => {} }) {
this.scene = scene;
this.terrain = terrain;
this.proj = projection;
this.base = baseUrl;
this.radius = radius;
this.onError = onError;
this.index = null;
this.tiles = new Map(); // clé → { mesh (ou null si dalle vide), tris } | 'loading'
this.origin = null;
this.visible = false;
this.enabled = true;
this.count = 0; // dalles chargées
this.disposed = false;
// Autour de l'utilisateur, on ignore les obstacles : sinon sa propre maison, l'arbre au-dessus de lui
// ou l'erreur GPS (qui le place « dans » un bâtiment voisin) cacheraient toute la vue.
this.clear = { center: { value: new THREE.Vector2() }, radius: { value: 12 } };
// DoubleSide : les pentes (murs) tournées vers l'utilisateur doivent cacher aussi, quel que soit leur sens
this.hidden = withClearZone(new THREE.MeshBasicMaterial({ colorWrite: false, side: THREE.DoubleSide }), this.clear);
this.shown = withClearZone(new THREE.MeshBasicMaterial({ color: 0x29b6f6, transparent: true, opacity: 0.35, side: THREE.DoubleSide }), this.clear);
this.ready = fetch(this.base + 'index.json')
.then((r) => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); })
.then((j) => { this.index = new Set(j.tiles); this.meta = j; this.build = j.build || '0'; })
.catch((e) => this.onError(`relief LiDAR non chargé (${e.message})`));
}
setOrigin(locar, lon, lat) {
const [X, Y] = this.proj.project(lon, lat);
const [wx, wz] = locar.lonLatToWorldCoords(lon, lat);
this.origin = [X - wx, Y + wz];
}
// Zone dégagée autour de la caméra (position monde x, z ; rayon en m)
setClearZone(x, z, radius) {
this.clear.center.value.set(x, z);
this.clear.radius.value = radius;
}
setVisible(v) {
this.visible = v;
for (const t of this.tiles.values()) if (t !== 'loading' && t.mesh) t.mesh.material = v ? this.shown : this.hidden;
}
setEnabled(v) {
this.enabled = v;
for (const t of this.tiles.values()) if (t !== 'loading' && t.mesh) t.mesh.visible = v;
}
update(lon, lat) {
if (!this.index || !this.origin || this.disposed) return;
const [X, Y] = this.proj.project(lon, lat);
this.me = [X, Y];
const need = new Set();
for (let kx = Math.floor((X - this.radius) / TILE); kx <= Math.floor((X + this.radius) / TILE); kx++) {
for (let ky = Math.floor((Y - this.radius) / TILE); ky <= Math.floor((Y + this.radius) / TILE); ky++) {
const key = `${kx}_${ky}`;
if (this.index.has(key)) need.add(key);
}
}
for (const key of need) if (!this.tiles.has(key)) this.load(key);
for (const [key, t] of this.tiles) {
if (need.has(key) || t === 'loading') continue;
const [kx, ky] = key.split('_').map(Number);
if (Math.hypot((kx + 0.5) * TILE - X, (ky + 0.5) * TILE - Y) > this.radius + 2 * TILE) this.unload(key);
}
}
unload(key) {
const t = this.tiles.get(key);
if (t && t !== 'loading') { if (t.mesh) { this.scene.remove(t.mesh); t.mesh.geometry.dispose(); } this.count--; }
this.tiles.delete(key);
}
dispose() {
this.disposed = true;
for (const key of [...this.tiles.keys()]) this.unload(key);
}
async load(key) {
this.tiles.set(key, 'loading');
try {
const r = await fetch(`${this.base}${key}.png?b=${this.build}`);
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const bmp = await createImageBitmap(await r.blob(), { colorSpaceConversion: 'none', premultiplyAlpha: 'none' });
const n = bmp.width;
const cv = typeof OffscreenCanvas !== 'undefined' ? new OffscreenCanvas(n, n) : Object.assign(document.createElement('canvas'), { width: n, height: n });
const cx = cv.getContext('2d', { willReadFrequently: true });
cx.drawImage(bmp, 0, 0);
bmp.close?.();
const rgba = cx.getImageData(0, 0, n, n).data;
await this.terrain.ensure(this.terrain.neighbours(key));
if (this.disposed || this.tiles.get(key) !== 'loading') return;
let h = new Uint8Array(n * n);
for (let i = 0; i < n * n; i++) h[i] = rgba[i * 4];
let res = TILE / n, m = n;
// Données 1 m : au-delà de 450 m, on regroupe par 2 × 2 (max) pour alléger le téléphone
const [kx, ky] = key.split('_').map(Number);
if (res < 2 && this.me && Math.hypot((kx + 0.5) * TILE - this.me[0], (ky + 0.5) * TILE - this.me[1]) > 450 + TILE * 0.71) {
m = n / 2; res *= 2;
const h2 = new Uint8Array(m * m);
for (let j = 0; j < m; j++) for (let i = 0; i < m; i++) {
const a = 2 * j * n + 2 * i;
h2[j * m + i] = Math.max(h[a], h[a + 1], h[a + n], h[a + n + 1]);
}
h = h2;
}
const X0 = kx * TILE, Y1 = (ky + 1) * TILE, T = this.terrain;
const ground = (i, j) => T.alt(X0 + i * res, Y1 - j * res); // coin (i, j) des pixels
const geom = heightfield(h, m, res, X0 - this.origin[0], ky * TILE - this.origin[1], this.meta.step || 0.2, ground);
if (!geom) { this.tiles.set(key, { mesh: null, tris: 0 }); this.count++; return; }
const mesh = new THREE.Mesh(geom, this.visible ? this.shown : this.hidden);
mesh.renderOrder = -1;
mesh.frustumCulled = false;
mesh.visible = this.enabled;
this.scene.add(mesh);
this.tiles.set(key, { mesh, tris: geom.index.count / 3 });
this.count++;
} catch (e) {
this.tiles.delete(key);
this.onError(`dalle LiDAR ${key} : ${e.message}`);
}
}
}
// Surface posée sur le sol (ground(i, j) = altitude du coin (i, j)) dont les sommets sont aux COINS des pixels,
// à la hauteur du plus haut des pixels qui touchent ce coin. Chaque bâtiment ou arbre devient un plateau continu
// dont les bords descendent jusqu'au sol sur une case : pas d'encoches en dents de scie dans les murs (avec des
// sommets aux centres des pixels, la ligne passait à travers des trous triangulaires). Un peu plus large que l'objet
// réel (une demi-case de chaque côté) : on préfère cacher un peu trop que pas assez.
// Monde : x = est, z = -nord, y = altitude. ox, oy = coin sud-ouest de la dalle dans le repère monde.
function heightfield(h, n, res, ox, oy, step, ground) {
const N = n + 1, hc = new Uint8Array(N * N);
for (let j = 0; j < n; j++) {
for (let i = 0; i < n; i++) {
const v = h[j * n + i];
if (!v) continue;
const k = j * N + i;
if (hc[k] < v) hc[k] = v;
if (hc[k + 1] < v) hc[k + 1] = v;
if (hc[k + N] < v) hc[k + N] = v;
if (hc[k + N + 1] < v) hc[k + N + 1] = v;
}
}
const vid = new Int32Array(N * N).fill(-1);
const pos = [], idx = [];
const v = (i, j) => {
const k = j * N + i;
if (vid[k] < 0) {
vid[k] = pos.length / 3;
pos.push(ox + i * res, ground(i, j) + hc[k] * step, -(oy + TILE - j * res));
}
return vid[k];
};
for (let j = 0; j < n; j++) {
for (let i = 0; i < n; i++) {
const k = j * N + i;
if (!(hc[k] | hc[k + 1] | hc[k + N] | hc[k + N + 1])) continue;
const a = v(i, j), b = v(i + 1, j), c = v(i, j + 1), d = v(i + 1, j + 1);
idx.push(a, c, b, b, c, d);
}
}
if (!idx.length) return null;
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
g.setIndex(pos.length / 3 > 65535 ? new THREE.Uint32BufferAttribute(idx, 1) : new THREE.Uint16BufferAttribute(idx, 1));
return g;
}