Boucle du Hainaut : application de réalité augmentée (v46)

PWA three.js + LocAR : pylônes et câbles de la ligne 380 kV sur le tracé
projeté, à l'échelle réelle, cachés par le relief (SPW 10 m), les obstacles
LiDAR (1/2/4 m) et les bâtiments OpenStreetMap. Photo avant/après, calage
de la vue, mini-carte, hors-ligne complet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mathieuandClaude Opus 5.5 committed 2026-11-15 22:19:19 +01:00
commit 3662fd4993
3571 files changed
+83668

No files matched your search

+226
View File
@@ -0,0 +1,226 @@
// Relief du terrain : altitude du sol (MNT SPW 2021-2022 moyenné à 10 m, + Flandre DHMV II).
// Dalles de 1 km : data/terrain/kx_ky.png, 100 × 100 px, altitude en décimètres = R × 256 + G,
// ligne 0 = nord ; le pixel (i, j) est centré à (i·10 + 5, 1000 − j·10 − 5) m du coin sud-ouest de la dalle.
//
// Repère monde de l'app : y = altitude (m, DNG). La caméra est à « sol sous l'utilisateur + 1,6 m »,
// les pylônes, bâtiments et arbres sont posés sur le sol à leur emplacement.
// TerrainOccluders : le sol lui-même, invisible, n'écrit que dans le tampon de profondeur :
// une colline entre l'utilisateur et un pylône le cache.
import * as THREE from 'three';
const TILE = 1000, PX = 100, RES = 10;
export class Terrain {
constructor({ baseUrl = 'data/terrain/', onError = () => {} } = {}) {
this.base = baseUrl;
this.onError = onError;
this.tiles = new Map(); // clé → Float32Array (m) | null (pas de données) | Promise (en cours)
this.def = 0; // altitude utilisée là où il n'y a pas de données (= sol sous l'utilisateur)
this.index = null;
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.index = new Set(); this.onError(`relief du terrain non chargé (${e.message})`); });
this._k = null; this._t = null; // dernière dalle consultée (accélère alt())
}
static keyOf(X, Y) { return `${Math.floor(X / TILE)}_${Math.floor(Y / TILE)}`; }
// Clés des dalles existantes dans un rayon r (m) autour du point projeté (X, Y)
keysAround(X, Y, r) {
const out = [];
if (!this.index) return out;
for (let kx = Math.floor((X - r) / TILE); kx <= Math.floor((X + r) / TILE); kx++) {
for (let ky = Math.floor((Y - r) / TILE); ky <= Math.floor((Y + r) / TILE); ky++) {
const key = `${kx}_${ky}`;
if (this.index.has(key)) out.push(key);
}
}
return out;
}
// La dalle et ses 8 voisines (pour un relief continu aux bords)
neighbours(key) {
const [kx, ky] = key.split('_').map(Number);
return this.keysAround((kx + 0.5) * TILE, (ky + 0.5) * TILE, TILE);
}
loaded(key) { const t = this.tiles.get(key); return t !== undefined && !(t instanceof Promise); }
load(key) {
const t = this.tiles.get(key);
if (t !== undefined) return t instanceof Promise ? t : Promise.resolve();
if (!this.index?.has(key)) { this.tiles.set(key, null); return Promise.resolve(); }
const p = (async () => {
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 cv = typeof OffscreenCanvas !== 'undefined' ? new OffscreenCanvas(PX, PX) : Object.assign(document.createElement('canvas'), { width: PX, height: PX });
const cx = cv.getContext('2d', { willReadFrequently: true });
cx.drawImage(bmp, 0, 0);
bmp.close?.();
const rgba = cx.getImageData(0, 0, PX, PX).data;
const a = new Float32Array(PX * PX);
for (let i = 0; i < PX * PX; i++) a[i] = (rgba[i * 4] * 256 + rgba[i * 4 + 1]) / 10;
this.tiles.set(key, a);
} catch (e) {
this.tiles.set(key, null); // sol supposé au niveau de l'utilisateur sur cette dalle
this.onError(`dalle de relief ${key} : ${e.message}`);
}
this._k = null;
})();
this.tiles.set(key, p);
return p;
}
async ensure(keys) {
await this.ready;
await Promise.all([...keys].map((k) => this.load(k)));
}
// Altitude d'un pixel (colonne c depuis l'ouest, rangée r depuis le sud, en pixels de 10 m) ou null
px(c, r) {
const kx = Math.floor(c / PX), ky = Math.floor(r / PX), k = kx * 100000 + ky;
if (k !== this._k) {
const t = this.tiles.get(`${kx}_${ky}`);
this._k = k; this._t = t instanceof Float32Array ? t : null;
}
if (!this._t) return null;
return this._t[(PX - 1 - (r - ky * PX)) * PX + (c - kx * PX)];
}
// Altitude du sol (m) au point projeté (X, Y), interpolée entre les 4 pixels voisins.
// def : valeur sans données (par défaut, le sol sous l'utilisateur)
alt(X, Y, def = this.def) {
const gx = (X - RES / 2) / RES, gy = (Y - RES / 2) / RES;
const c = Math.floor(gx), r = Math.floor(gy), fx = gx - c, fy = gy - r;
let s = 0, w = 0, v, k;
if ((v = this.px(c, r)) !== null) { k = (1 - fx) * (1 - fy); s += v * k; w += k; }
if ((v = this.px(c + 1, r)) !== null) { k = fx * (1 - fy); s += v * k; w += k; }
if ((v = this.px(c, r + 1)) !== null) { k = (1 - fx) * fy; s += v * k; w += k; }
if ((v = this.px(c + 1, r + 1)) !== null) { k = fx * fy; s += v * k; w += k; }
return w > 1e-6 ? s / w : def;
}
}
// Le sol comme écran invisible, sur un rayon de quelques km (précision réduite au loin)
export class TerrainOccluders {
constructor({ scene, projection, terrain, radius = 6000 }) {
this.scene = scene;
this.proj = projection;
this.terrain = terrain;
this.radius = radius;
this.tiles = new Map(); // clé → { mesh, step } | 'loading'
this.origin = null;
this.enabled = true;
this.disposed = false;
this.clear = { center: { value: new THREE.Vector2() }, radius: { value: 20 } };
this.material = withClearZone(new THREE.MeshBasicMaterial({ colorWrite: false, side: THREE.DoubleSide }), this.clear);
}
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];
}
setClearZone(x, z, radius) { this.clear.center.value.set(x, z); this.clear.radius.value = radius; }
setEnabled(v) {
this.enabled = v;
for (const t of this.tiles.values()) if (t !== 'loading') t.mesh.visible = v;
}
// Pas de la grille selon la distance de la dalle : 10 m près, 25 m, puis 50 m au loin
static stepFor(d) { return d < 1500 ? 10 : d < 3500 ? 25 : 50; }
async update(lon, lat) {
if (!this.origin || this.disposed) return;
await this.terrain.ready;
const [X, Y] = this.proj.project(lon, lat);
const need = new Map();
for (const key of this.terrain.keysAround(X, Y, this.radius)) {
const [kx, ky] = key.split('_').map(Number);
const d = Math.hypot((kx + 0.5) * TILE - X, (ky + 0.5) * TILE - Y);
if (d < this.radius + 700) need.set(key, TerrainOccluders.stepFor(d));
}
for (const [key, step] of need) {
const t = this.tiles.get(key);
if (t === 'loading' || (t && t.step === step)) continue;
this.build(key, step);
}
for (const [key, t] of this.tiles) {
if (need.has(key) || t === 'loading') continue;
this.remove(key);
}
}
remove(key) {
const t = this.tiles.get(key);
if (t && t !== 'loading') { this.scene.remove(t.mesh); t.mesh.geometry.dispose(); }
this.tiles.delete(key);
}
dispose() {
this.disposed = true;
for (const key of [...this.tiles.keys()]) this.remove(key);
}
async build(key, step) {
const old = this.tiles.get(key);
this.tiles.set(key, 'loading');
await this.terrain.ensure(this.terrain.neighbours(key));
if (this.disposed || this.tiles.get(key) !== 'loading') return;
if (old && old !== 'loading') { this.scene.remove(old.mesh); old.mesh.geometry.dispose(); }
const [kx, ky] = key.split('_').map(Number);
const n = TILE / step + 1, X0 = kx * TILE, Y0 = ky * TILE, [ox, oy] = this.origin;
const pos = new Float32Array((n * n + 4 * n) * 3), idx = [];
for (let j = 0; j < n; j++) {
for (let i = 0; i < n; i++) {
const X = X0 + i * step, Y = Y0 + j * step, o = (j * n + i) * 3;
pos[o] = X - ox; pos[o + 1] = this.terrain.alt(X, Y); pos[o + 2] = -(Y - oy);
}
}
for (let j = 0; j < n - 1; j++) {
for (let i = 0; i < n - 1; i++) {
const a = j * n + i, b = a + 1, c = a + n, d = c + 1;
idx.push(a, b, c, b, d, c);
}
}
// « Jupes » verticales le long des bords : bouchent les fentes entre dalles de pas différents
let v = n * n;
const edges = [
Array.from({ length: n }, (_, i) => i), // sud
Array.from({ length: n }, (_, i) => (n - 1) * n + i), // nord
Array.from({ length: n }, (_, j) => j * n), // ouest
Array.from({ length: n }, (_, j) => j * n + n - 1), // est
];
for (const e of edges) {
const first = v;
for (const k of e) { pos[v * 3] = pos[k * 3]; pos[v * 3 + 1] = pos[k * 3 + 1] - 15; pos[v * 3 + 2] = pos[k * 3 + 2]; v++; }
for (let q = 0; q < n - 1; q++) idx.push(e[q], e[q + 1], first + q, e[q + 1], first + q + 1, first + q);
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
g.setIndex(v > 65535 ? new THREE.Uint32BufferAttribute(idx, 1) : new THREE.Uint16BufferAttribute(idx, 1));
const mesh = new THREE.Mesh(g, this.material);
mesh.renderOrder = -2; // avant tout le reste
mesh.frustumCulled = false;
mesh.visible = this.enabled;
this.scene.add(mesh);
this.tiles.set(key, { mesh, step });
}
}
// Ajoute au matériau un « trou » circulaire (dans le plan horizontal) autour de la caméra
export function withClearZone(mat, u) {
mat.onBeforeCompile = (sh) => {
sh.uniforms.clearCenter = u.center;
sh.uniforms.clearRadius = u.radius;
sh.vertexShader = 'varying vec2 vWorldXZ;\n' + sh.vertexShader.replace('#include <project_vertex>',
'#include <project_vertex>\n vWorldXZ = (modelMatrix * vec4(transformed, 1.0)).xz;');
sh.fragmentShader = 'uniform vec2 clearCenter;\nuniform float clearRadius;\nvarying vec2 vWorldXZ;\n'
+ sh.fragmentShader.replace('void main() {', 'void main() {\n if (distance(vWorldXZ, clearCenter) < clearRadius) discard;');
};
return mat;
}