build-geocoder 0.2.0

Build an offline FTS5 + R*Tree address database for cesium-viewer --geocoder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# cesiumjs-gdal-gpu-tiler — GPGPU-First GDAL to CesiumJS `quantized-mesh-1.0`, OGC 3D Tiles 1.1, Orthoimagery & Draped Cadastral MVT Engine

[![CI](https://github.com/kaktus40/cesiumjs-gdal-gpu-tiler/actions/workflows/ci.yml/badge.svg)](https://github.com/kaktus40/cesiumjs-gdal-gpu-tiler/actions/workflows/ci.yml)
[![Release](https://github.com/kaktus40/cesiumjs-gdal-gpu-tiler/actions/workflows/release.yml/badge.svg)](https://github.com/kaktus40/cesiumjs-gdal-gpu-tiler/actions/workflows/release.yml)
[![License: MIT OR Apache-2.0](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue.svg)](Cargo.toml)

A complete, provider-agnostic **Rust + GDAL + WebGPU (`wgpu`)** geospatial tiling suite that converts any GDAL-readable **Digital Elevation Model (DEM)**, any OGR-readable **3D vector dataset**, any GDAL-readable **aerial/satellite orthoimagery** (GeoTIFF, COG, JPEG2000, Sentinel-2, NAIP, national ortho), and any OGR-readable **2D/3D vector dataset** into CesiumJS-ready and Mapbox-compatible tile pyramids:

1. **`cesium-tiler` — Core GPGPU Tiling Engine (`quantized-mesh-1.0`, OGC 3D Tiles 1.1 & Orthoimagery)** *(worldwide, provider-agnostic)*:
   - **`build`**: Converts DEMs into **CesiumJS `quantized-mesh-1.0`** terrain pyramids (GPU RTIN/LEB, 1D adaptive borders, oct-encoded normals ext 1, coastal + vector watermask ext 2, subtree availability ext 4, multi-resolution VRT, WGS84 geoid undulation, Morton Z-order streaming, crash-safe `--resume`).
   - **`build3dtiles`**: Converts 3D vector datasets (including native `.osm.pbf` via [`cesium-osm`](crates/cesium-osm/)) into **OGC 3D Tiles 1.1** pyramids (`.glb` + `tileset.json` + external `z = 10` sub-tilesets, earcut with courtyard holes, hipped/gabled roofs, 3D lattice towers, bridges/dams/sports fields, zero-duplication `refine: "ADD"` multi-LOD, `EXT_mesh_features` + `EXT_structural_metadata`).
   - **`build-imagery`**: Converts orthoimagery rasters into **MBTiles 1.3 (`.mbtiles` / `.sqlite`)** or static **TMS directories** (`WebP` / `JPEG` / `PNG`, `EPSG:3857` Web Mercator or `EPSG:4326` Geodetic, direct spatial tile mosaic with per-thread LRU handles — zero VRT proxy-pool contention, premultiplied-alpha 2×2 box downsampling, constant-memory Morton streaming, crash-safe `--resume`).
   - **`build-vector`**: Converts any OGR vector datasets (`.shp`, `.gpkg`, `.fgb`, `.geojson`, `.parquet`) or native `.osm.pbf` extracts ([`cesium-osm`](crates/cesium-osm/)) into a **Mapbox-style vector/raster pyramid** (`--tile-format webp` [default, smallest footprint] / `png` transparent 256×256 RGBA tiles for 60 FPS CesiumJS draping, or `--tile-format mvt` `.pbf`) driven by a Mapbox/MapLibre GL Style v8 JSON (`--style style.json` with `sources`, `layers`, `minzoom`/`maxzoom`, `filter`, `paint`, `layout`).
2. **`cesium-export` — Standalone Zero-Dependency Static Pyramid Exporter** *(worldwide)*:
   - Unpacks `.sqlite` / `.mbtiles` **terrain**, **3D Tiles 1.1**, **orthoimagery**, or **offline geocoder** archives into physical `{z}/{x}/{y}.terrain` / `.glb` / `.webp|.jpg|.png` files + `layer.json` / `tileset.json` / TMS `tilemapresource.xml` / WMTS `WMTSCapabilities.xml` / XYZ `tilejson.json` / `geocoder.json` + ready-to-use Apache (`.htaccess`) and Nginx configs (**~42,000 tiles/s**). Imagery is **never transcoded** (WebP stays WebP). Geocoders can also be exported to PostGIS SQL (`--to-postgis`) or MySQL/MariaDB SQL (`--to-mysql`).
   - **Zero external runtime dependencies** (statically bundles SQLite & pure-Rust gzip — **no GDAL, no system SQLite, no GPU required**; drop the single binary onto any bare production web server).
3. **`cesium-viewer` — Standalone Test & Visualization HTTP/1.1 Server** *(worldwide)*:
   - Dedicated testing & preview server with an embedded **CesiumJS 3D viewer** (`7,280 req/s`, HTTP/1.1 Keep-Alive + SQLite pool, simultaneous Terrain + repeatable named `--tiles3d NAME=PATH` sources + offline `--imagery` + `--geocoder` address search + custom `--wms-url` / `--wms-layer`).
   - Completely isolated from `cesium-tiler` with **zero GDAL and zero external SQLite dependencies**.
4. **`cesium-ign-downloader` — Optional France / IGN Geoplateforme Companion Downloader** *(France-specific)*:
   - Native Rust client for the official French IGN Geoplateforme Atom (`gpf_dl`) API (`https://data.geopf.fr/telechargement/`), supporting BD ORTHO®, RGE ALTI®, BD ALTI®, BD TOPO® (layer-by-layer GeoParquet/FlatGeoBuf with exact sizes), BD PARCELLAIRE® / Parcellaire Express (PCI), LiDAR HD, and PLAN IGN.
   - Features 7-day cached volume estimation, interactive + non-interactive CLI modes, anti-HTTP 429 `aria2c` downloads (`curl` fallback), async `7z` extraction + flat `.jp2`/`.tif` consolidation (`--flatten`), parallel ASCII DEM → Float32 GeoTIFF conversion, and atomic `.download-session.json` resume.

![From regular DEM to adaptive TIN and CesiumJS pyramid](docs/images/01_dem_vers_tin.png)

---

## Prerequisites & System Dependencies

The four executables have intentionally distinct dependency profiles so you only install heavy GIS libraries on the build machine (and the 3 core tools stay 100% worldwide and provider-agnostic):

| Executable | Scope & Purpose | Runtime Prerequisites | Build Prerequisites (from source) |
|---|---|---|---|
| **`cesium-tiler`** | **Worldwide** — Generate `quantized-mesh-1.0`, OGC 3D Tiles 1.1 & orthoimagery pyramids | **GDAL** (`libgdal` + PROJ data) · Optional **`libdeflate`** (unless built with `--no-default-features`) · Optional **Vulkan / Metal / DX12** GPU driver (`--cpu-only` works without GPU) · Optional **NVIDIA CUDA + `nvJPEG2000`** (`libnvjpeg2k.so.0` + `libcudart.so`, runtime-loaded via `dlopen` for GPU `.jp2` decoding) · *SQLite is statically bundled* | Rust 1.75+, C/C++ toolchain, `libgdal-dev`, `libclang-dev`, `pkg-config`, optional `libdeflate-dev` *(no CUDA SDK required at compile time)* |
| **`cesium-export`** | **Worldwide** — Convert `.sqlite` / `.mbtiles` archive → static terrain / 3D Tiles / imagery files for Apache/Nginx | **None** (100% self-contained: **no GDAL, no system SQLite, no GPU, no libdeflate**) | Rust 1.75+, C compiler (to compile bundled SQLite) |
| **`cesium-viewer`** | **Worldwide** — Local HTTP/1.1 test server & CesiumJS 3D visualization viewer | **None** (100% self-contained: **no GDAL, no system SQLite, no GPU, no libdeflate**) | Rust 1.75+, C compiler (to compile bundled SQLite) |
| **`cesium-ign-downloader`** | **France (IGN)** — Optional Geoplateforme Atom (`gpf_dl`) dataset downloader & extractor | **`curl`** (API requests & fallback download) · Optional **`aria2c`** (fast multi-stream downloads), **`7z`** (`.7z` extraction), **`gdal_translate`** (ASCII DEM conversion) — **zero linked shared libraries beyond libc** | Rust 1.75+ (zero C/GDAL build dependencies) |

### Installing Prerequisites for `cesium-tiler`
```bash
# Ubuntu / Debian (runtime only for prebuilt binary)
sudo apt install libgdal34t64 libdeflate0

# Ubuntu / Debian (full build from source)
sudo apt install libgdal-dev libdeflate-dev libclang-dev pkg-config build-essential

# Arch Linux
sudo pacman -S gdal libdeflate clang pkgconf base-devel
# Optional (NVIDIA GPU acceleration for .jp2 imagery via runtime dlopen):
# sudo pacman -S cuda   # + extract NVIDIA nvJPEG2000 tarball into /opt/cuda/{include,lib64} && sudo ldconfig

# macOS (Homebrew)
brew install gdal libdeflate

# Windows (prebuilt zip): GDAL, PROJ, and libdeflate DLLs are bundled in the release archive.
```

> **Tip for bare production web servers:** You do **not** need GDAL, PROJ, SQLite, or GPU drivers on your Apache/Nginx hosting server — copy only the standalone `cesium-export` binary to unpack your `.sqlite` archive directly into `/var/www/`.

---

## Measured Benchmarks (RTX 5060 Laptop GPU + 24-Thread CPU)

| Dataset | Zoom / Error | Output Produced | SQLite Size | Build Time |
|---|---|---|---:|---:|
| **National 1 m LiDAR DEM (France + Corsica + DROM-COM, geoids + 992k hydro)** | `z = 0..18`, `E = 1.0 m` | Full national `quantized-mesh-1.0` + Ext 1/2/4 | **81 GiB** | Overnight (~16k tiles/s peak) |
| **National 25 m DEM** (geoids + 992k hydro polygons) | `z = 0..14`, `E = 1.0 m` | **928,956 tiles** · 1.85B triangles | **13 GiB** | ~13–32 min |
| **Urban 1 m LiDAR (`D075` Paris, 138 tiles)** | `z = 0..18`, `E = 1.0 m` | **48,852 tiles** · 597 B/tile avg at `z = 18` | **50 MiB** | **2.9 s** (16,926 tiles/s) |
| **Alpine 1 m LiDAR (`D005` Alps sample, 40 tiles)** | `z = 0..18`, `E = 1.0 m` | **13,480 tiles** · 674 B/tile avg at `z = 18` | **22 MiB** | **4.0 s** (3,342 tiles/s) |
| **National 3D Buildings (49.9M features)** | `z = 12..14`, `refine: ADD` | **599,581 `.glb` tiles** · 2,431 sub-tilesets | **20 GiB** | 28 min 44 s |
| **Standalone Test Server (`cesium-viewer`)** | HTTP/1.1 Keep-Alive + SQLite pool | Terrain + 3D Tiles + Offline Imagery | RAM < 100 MiB | **7,280 req/s** |
| **Standalone Static Exporter (`cesium-export`)** | SQLite/MBTiles → Apache/Nginx files | `.terrain` / `.glb` / `.webp` + `.htaccess` | — | **42,025 tiles/s** |

### Comparative Terrain Benchmark (3 × 1 m Departments, `z = 0..17`, 62 GiB RAM)

Reproducible native-binary comparison ([`bench/benchmark_terrain.sh`](bench/benchmark_terrain.sh)) on **IGN RGE ALTI 1 m** (`40` Landes flat, `29` Finistère coastal, `73` Savoie alpine — `z=0..17`, `E=1.0 m`, `--format dir` writing `.terrain` files directly):

| Tool | Completed | Prep (`gdalwarp`) | Conversion | Total Time | Peak RAM | Throughput |
|---|---|---:|---:|---:|---:|---:|
| **`cesium-tiler`** | **3 / 3** | **0.0 s** *(reads `EPSG:2154` directly)* | **253.5 s (4 min 14 s)** | **253.5 s** | **2.53–2.60 GiB** | **7,034–7,970 tiles/s** |
| `ctb-tile` (`ahuarte47`) | 0 / 3 *(OOM `SIGKILL`)* | 1,461.9 s *(24 min 22 s)* | >2,931.6 s *(partial)* | >4,393.4 s *(>73 min)* | **43.8–50.2 GiB** | 1,258–1,442 tiles/s |
| `tin-terrain` (`heremaps`) | 0 / 3 *(`bad_alloc`/OOM)* | 1,580.7 s *(26 min 21 s)* | 186.4 s *(0 tiles)* | 1,767.1 s *(~29 min)* | up to **52.3 GiB** | 0 tiles/s |

- **Zero preparation overhead**: `ctb-tile` (`EPSG:4326`) and `tin-terrain` (`EPSG:3857`) spend **24–26 minutes** in `gdalwarp` reprojection *alone* (6× longer than `cesium-tiler`'s entire 3-department build!) before tiling even begins.
- **Constant ~2.6 GiB RAM vs 44–52 GiB OOM**: `cesium-tiler` completes all 3 departments (`1,941,088` tiles, `8.4 GiB`) in **4 min 14 s** while both C++ competitors exhaust 62 GiB RAM (and still fail `0/3` even at `5 m`, `z = 0..10`).
- **Head-to-head on `3 × 10 km × 10 km` crops (`1 m`, `z = 0..17`, where all 3 tools succeed `3/3`)**: `cesium-tiler` completes all 3 zones in **`4.26 s` total** (`1.42 s` each, `5,720–5,982 tiles/s`, `1.5 GiB` RAM) vs **`40.91 s`** (`9.6×` slower, `8.5–9.5 GiB` RAM) for `ctb-tile` and **`126.77 s`** (`29.8×` slower, up to `57.2×` slower in alpine Savoie) for `tin-terrain`.
- Full breakdown across all 3 campaigns (`1 m` departments, `5 m z=0..10`, and `10 km` crops): **[`bench/ANALYSIS.md`](bench/ANALYSIS.md)**.

---

## Quick Start (60 Seconds)

### 1. Inspect Hardware & Generate a Host-Tailored `cesium-tiler.toml`
`cesium-tiler init` inspects your CPU cores, RAM, all Vulkan/Metal/DX12 GPU adapters, GDAL version, available disk space, and local geoid grids, then interactively builds a **didactic, self-documented `cesium-tiler.toml`** (including host-specific choices in comments and the exact CLI override flag for every single option):

```bash
# Interactive hardware-aware setup wizard (recommended first step)
./cesium-tiler init

# Or generate non-interactively using a resource preset (workstation | balanced | dedicated)
./cesium-tiler init --profile workstation --non-interactive
```

### 2. Run a 30-Second End-to-End Test
```bash
# 1. Inspect detected hardware (CPU, RAM, GPUs, disk, geoids, GDAL)
./cesium-tiler info

# 2. Generate a synthetic alpine GeoTIFF and build a quantized-mesh-1.0 pyramid
./cesium-tiler generate-test-dem -o demo.tif
./cesium-tiler build -i demo.tif -o demo.sqlite

# 3. Preview in the standalone CesiumJS 3D test & visualization server
./cesium-viewer demo.sqlite
# -> Open http://127.0.0.1:8080/

# 4. (Optional) Export SQLite archive to static Apache/Nginx files (zero GDAL/SQLite deps!)
./cesium-export -i demo.sqlite -o ./www_terrain --web-config
```

### 3. Production Example (Complete Offline Stack: Terrain + 3D Tiles + Imagery + Styled Vector Overlay)
```bash
# 1. Terrain pyramid (auto-loads ./cesium-tiler.toml; CLI flags override file settings for this run)
./cesium-tiler build \
  -i ./data/dem_folder \
  -o ./output/terrain.sqlite \
  --max-zoom 18 --max-error 1.0 --gzip-level 9 \
  --watermask-below 0.5 \
  --watermask-vector ./data/water_polygons.parquet \
  --resume

# 2. OGC 3D Tiles 1.1 pyramid (Overture Maps, OSM, GeoPackage, GeoParquet, FlatGeobuf, GeoJSON...)
./cesium-tiler build3dtiles \
  -i ./data/buildings.parquet \
  -o ./output/buildings_3dtiles.sqlite

# 3. Orthoimagery pyramid (GeoTIFF, COG, JPEG2000; multi-resolution VRT stacking supported)
./cesium-tiler build-imagery \
  -i ./data/ortho_5m \
  -i ./data/ortho_20cm_city \
  -o ./output/imagery.mbtiles \
  --tile-format webp --quality 82 --max-zoom 18

# 4. Vector pyramid (Mapbox GL Style v8 JSON -> styled RGBA .webp [default], .png, or MVT .pbf)
./cesium-tiler build-vector \
  --style ./style.json \
  -o ./output/vectors.mbtiles \
  --tile-format webp --quality 55 \
  --min-zoom 8 --max-zoom 14

# 5. Preview locally (100% offline capable!)
#    --tiles3d and --imagery are repeatable (PATH or NAME=PATH); extra --imagery layers drape on top.
./cesium-viewer ./output/terrain.sqlite \
  --tiles3d batiments=./output/buildings_3dtiles.sqlite \
  --imagery ortho=./output/imagery.mbtiles \
  --imagery vectors=./output/vectors.mbtiles \
  --geocoder ./output/addresses.sqlite

# 6. Export any archive to static Apache/Nginx files on any bare web server (no GDAL, no SQLite needed)
./cesium-export -i ./output/terrain.sqlite -o /var/www/terrain --web-config --resume
./cesium-export -i ./output/imagery.mbtiles -o /var/www/imagery --web-config --resume
# -> TMS tiles + complete tilemapresource.xml (Cesium TileMapServiceImageryProvider.fromUrl)
./cesium-export -i ./output/imagery.mbtiles -o /var/www/imagery_wmts \
  --service wmts --wmts-base-url https://example.com/imagery --web-config
# -> XYZ tiles + WMTSCapabilities.xml (RESTful ResourceURL)
./cesium-export -i ./output/addresses.sqlite -o /var/www/geocoder \
  --to-postgis /var/www/geocoder/addresses_postgis.sql --web-config
# -> geocoder.json + addresses.sqlite (copy) + PostGIS SQL dump
```

---

## Configuration System & Precedence (`cesium-tiler.toml` + CLI)

`cesium-tiler` supports persistent machine/project configuration via **`cesium-tiler.toml`** with strict, predictable precedence:

1. **Explicit CLI flags** passed on the command line (highest priority — overrides `cesium-tiler.toml` for that single run only, including symmetric boolean toggles such as `--no-low-priority` or `--force-borders`).
2. **Configuration file** (`--config <PATH>`, or automatically loaded from `./cesium-tiler.toml` in the working directory unless `--no-config` is passed).
3. **Built-in defaults** (lowest priority).

### Note on Geoid Grids (`RAF20`, `RAC23`, `EGM2008`, etc.)
Geoid undulation grids are **official external PROJ/GDAL rasters — they are NOT generated by `cesium-tiler`**.
When `--vertical-datum wgs84` is active (the default for CesiumJS), `cesium-tiler-core` applies a 3-tier strategy:
1. Any raster grid (`.tif`, `.gtx`, `.byn`, `.grd`, `.pgm`) passed via `--geoid-grid` or placed in `./geoids/` (sorted finest-first, so national centimeter grids automatically take priority over global grids).
2. System PROJ grid directories (`$PROJ_DATA`, `~/.local/share/proj/`, `/usr/share/proj/`).
3. Built-in offline fallback model (so builds work even with zero external grid files).

To download official centimeter-accurate grids from the PROJ CDN:
```bash
mkdir -p geoids
# Global EGM2008 (~75 MiB) or national grids (e.g. IGN France RAF20 / RAC23):
curl -fSL -o geoids/us_nga_egm08_25.tif https://cdn.proj.org/us_nga_egm08_25.tif
curl -fSL -o geoids/fr_ign_RAF20.tif    https://cdn.proj.org/fr_ign_RAF20.tif
```

---

## Complete Parameter Reference (`cesium-tiler.toml` & CLI Flags)

Every configurable parameter is documented below with its **`cesium-tiler.toml` key**, **CLI flag(s)**, **default value**, and **operational implications** (storage, speed, memory, visual quality).

### Global CLI Flags (All Subcommands)

| CLI Flag | Default | Description & Implications |
|---|---|---|
| `-c, --config <PATH>` | `./cesium-tiler.toml` (auto) | Load a specific TOML configuration file. If omitted and `./cesium-tiler.toml` exists in the current directory, it is loaded automatically. |
| `--no-config` | `false` | Ignore any `./cesium-tiler.toml` in the current directory and run strictly with built-in defaults + explicit CLI flags. Useful for reproducible CI scripts. |

---

### Section `[hardware]` — Compute Backend & Resource Allocation

Applies to `build`, `build3dtiles` (`workers`), and `export` (`workers`).

| `cesium-tiler.toml` Key | CLI Override Flag(s) | Default | Implications & Tuning Guidance |
|---|---|---|---|
| `hardware.profile` | *(set by `cesium-tiler init --profile`)* | `"workstation"` | Informational preset label (`workstation`, `balanced`, `dedicated`, `custom`). `workstation` keeps your desktop responsive during multi-hour builds; `dedicated` saturates 100% of CPU, GPU, and NVMe bandwidth. |
| `hardware.cpu_only` | `--cpu-only` / `--gpu` | `false` | Forces the bit-exact CPU reference RTIN engine instead of `wgpu`. **Implication:** ~5×–10× slower than a discrete GPU, but requires zero GPU drivers (ideal for headless CI/cloud VMs). |
| `hardware.gpu_adapter` | `--gpu-adapter <STR>` | `""` (auto) | Case-insensitive substring matching a `wgpu` GPU adapter name (e.g. `"RTX"`, `"Radeon"`, `"Apple"`). Run `cesium-tiler info` to list exact names. **Implication:** prevents `wgpu` from picking an integrated GPU or software `llvmpipe` renderer on multi-GPU laptops. |
| `hardware.workers` | `--workers <N>` | `0` (auto: `cores - 2`) | Rayon thread pool size for tile encoding, `libdeflate` gzip, 3D Tiles extrusion, and static export. **Implication:** higher values speed up encoding linearly until disk/GDAL becomes the bottleneck; reserving 2 threads keeps desktop apps snappy. |
| `hardware.gdal_readers` | `--gdal-readers <N>` | `0` (auto: `1..4`) | Parallel GDAL super-tile reader threads (terrain GPU batches / imagery direct-source reads). **Implication:** 4–8 readers saturate NVMe SSDs, but each reader keeps up to 12 open GDAL datasets in RAM (~100–250 MiB/thread). For JP2, descend to `1` if OpenJPEG crashes — see the JPEG 2000 note below. |
| `hardware.batch_size` | `--batch-size <64\|256>` | `256` | Number of leaf tiles processed per GPU super-tile batch (`256` = 16×16, `64` = 8×8). **Implication:** `256` uses ~154 MiB VRAM and minimizes GDAL read overhead; `64` drops VRAM usage to ~40 MiB for low-VRAM GPUs. |
| `hardware.low_priority` | `--low-priority` / `--no-low-priority` | `false` | Sets Linux `nice +15` and `ionice` idle class. **Implication:** eliminates UI/audio/IDE stutter during background builds with negligible (< 5%) slowdown on an otherwise idle machine. |
| `hardware.gpu_yield_ms` | `--gpu-yield-ms <MS>` | `0` | Millisecond pause between GPU super-tiles. **Implication:** `0` maximizes throughput; `2–10` ms lowers laptop fan noise/thermals and prevents desktop compositor frame drops while working alongside a build. |

---

### Section `[paths]` — Output Directories, Storage Container & Geoids

| `cesium-tiler.toml` Key | CLI Override Flag(s) | Default | Implications & Tuning Guidance |
|---|---|---|---|
| `paths.output_dir` | `-o, --output <PATH>` | `"./output"` | Default output directory used when `-o` is omitted or passed as a bare filename (e.g. `-o france.sqlite` resolves to `<output_dir>/france.sqlite`). Passing a path with a directory separator (e.g. `-o /mnt/ssd/a.sqlite`) always uses that exact path. |
| `paths.format` | `--format <sqlite\|dir>` | `"sqlite"` (in `cesium-tiler.toml`) / auto | Storage backend. **`sqlite`** (recommended): single ACID file with 16 KiB B-tree pages, WAL journal, zero inode exhaustion, instant `--resume`, directly servable by `cesium-tiler serve` or exported later. **`dir`**: writes millions of physical `{z}/{x}/{y}.terrain` files directly (can exhaust ext4 inodes and slows down copies/deletes). Auto-selects `sqlite` whenever `-o` ends in `.sqlite`, `.mbtiles`, or `.db`. |
| `paths.geoid_grid` | `--geoid-grid <PATH>` | `""` (auto) | Explicit geoid raster file or folder (`.tif`, `.gtx`, `.byn`, `.grd`, `.pgm`). When empty, auto-discovers `./geoids/` and system PROJ paths before falling back to the built-in offline model. **Implication:** improves vertical alignment with GPS/WGS84 imagery from ~1–3 m to ±1–2 cm. |

---

### Section `[terrain]` — Quantized-Mesh 1.0 Pyramid (`cesium-tiler build`)

| `cesium-tiler.toml` Key | CLI Override Flag(s) | Default | Implications & Tuning Guidance |
|---|---|---|---|
| *(CLI only)* | `-i, --input <PATH>...` | *(required)* | One or more input DEM files or directories. Directories are scanned recursively, deduplicated, grouped by CRS, and stacked coarsest → finest automatically. |
| *(CLI only)* | `--source-srs <SRS>` | auto | Overrides the source CRS (e.g. `"EPSG:2154"`) for rasters lacking embedded projection metadata. |
| `terrain.auto_vrt` | `--no-auto-vrt` / `--auto-vrt` | `true` | Automatically builds a unified multi-resolution GDAL VRT in `<work_dir>/.tin_vrt/source.vrt`. Disable only when feeding a single pre-built `.vrt` or GeoTIFF directly. |
| `terrain.min_zoom` | `--min-zoom <Z>` | `0` | Coarsest TMS zoom level generated. **Implication:** CesiumJS requires `min_zoom = 0` so root globe tiles exist. |
| `terrain.max_zoom` | `--max-zoom <Z>` | `0` (auto) | Finest TMS zoom level (`0` = computed automatically from DEM resolution). **Major implication:** each `+1` zoom level multiplies total tile count, disk size, and build time by **~4×** (`z=14` ≈ 14 m/sample for 25 m DEMs; `z=16` ≈ 3.4 m; `z=17` ≈ 1.7 m; `z=18` ≈ 0.85 m for 1 m LiDAR). |
| `terrain.max_error` | `--max-error <METERS>` | `1.0` | Maximum vertical geometric error in meters at `z_max` (doubles at every coarser zoom level: `E(z) = max_error * 2^(z_max - z)`). **Major implication:** directly controls mesh density and disk footprint. `0.5 m` gives ultra-crisp cliffs (~1.8× larger); `1.0 m` is the balanced sweet spot; `1.5–2.0 m` yields compact archives on national 1 m builds. |
| `terrain.error_mode` | `--error-mode <max\|strict>` | `"max"` | RTIN bottom-up error propagation rule. **`max`** (Martini): compact meshes with tight practical accuracy. **`strict`** (Evans additive bound): mathematically guaranteed upper error bound across all triangles (~20–40% more triangles). |
| `terrain.feature_d2_abs` | `--feature-d2-abs <METERS>` | `0.0` (off) | Optional 2nd-order vertical curvature breakline filter in meters. When `> 0`, sharp ridges/cliffs exceeding this curvature are forced into the mesh even if below `max_error`. **Implication:** `0.0` (default) lets exact RTIN control triangle budget cleanly; small non-zero values increase triangle count and disk footprint. |
| `terrain.feature_d2_slope` | `--feature-d2-slope <M/M>` | `0.0` (off) | Optional 2nd-order slope breakline filter (m/m). Guarded by `max_abs >= 0.5 * max_error` so sub-tolerance micro-noise at `z = 17..18` never bloats tiles. **Implication:** `0.0` (default) is fastest and most compact; opt in (e.g. `0.25`) only when accentuating sharp escarpments. |
| `terrain.adaptive_borders` | `--adaptive-borders` / `--force-borders` | `true` | Uses 1D adaptive RTIN borders instead of locking all 256 perimeter vertices on every tile. **Major implication:** reduces archive size by **3×–5×** on flat/rolling terrain with zero cracks between same-zoom tiles. Low zoom levels (`z <= 5`) automatically retain curved borders to preserve 3D Earth curvature. |
| `terrain.vertical_datum` | `--vertical-datum <wgs84\|preserve>` | `"wgs84"` | **`wgs84`**: converts orthometric MSL elevations to WGS84 ellipsoidal heights (`h = H + N`) required by CesiumJS. **`preserve`**: leaves input elevations untouched (use if source DEM is already ellipsoidal WGS84). |
| `terrain.vertical_shift` | `--vertical-shift <METERS>` | `0.0` | Constant vertical offset added to all vertex heights (useful for datum calibration or bathymetry offset). |
| `terrain.include_normals` | `--no-normals` / `--normals` | `true` | Embeds Cesium Extension 1 (`octvertexnormals`, 2 bytes/vertex). **Implication:** enables dynamic solar hillshading and realistic lighting in CesiumJS for ~+15% archive size. |
| `terrain.watermask_below` | `--watermask-below <METERS>` | `""` (off) | Emits Cesium Extension 2 (`watermask`) marking orthometric heights `<= threshold` (e.g. `0.5` m) as animated ocean/coastal water. **Implication:** tiny size cost on uniform tiles (1 byte), 256×256 mask only along coastlines. |
| `terrain.watermask_vector` | `--watermask-vector <PATH>` | `""` (off) | OGR vector water polygon layer (`.parquet`, `.fgb`, `.gpkg`, `.shp`, `.geojson`) burned into Extension 2 and OR-merged with `watermask_below` for inland lakes and rivers. **Implication:** indexed once in RAM (~4 s for 1M polygons); adds ~1–5% overhead on tiles crossed by rivers/lakes. |
| `terrain.metadata_availability` | `--metadata-availability <N>` | `0` (off) / `10` (wizard) | Embeds Cesium Extension 4 subtree availability JSON into tiles at every `z % N == 0` (`0` disables). **Major implication:** essential for large/national pyramids (`10` recommended) — keeps `layer.json` under **~1 KiB** instead of tens of megabytes and eliminates CesiumJS startup lag. |
| `terrain.gzip` | `--no-gzip` / `--gzip` | `true` | Gzip-compresses `.terrain` payloads using thread-local `libdeflate` (or `flate2` fallback). **Implication:** ~3× smaller archives and directly compatible with `Content-Encoding: gzip` in CesiumJS/Nginx/Apache. |
| `terrain.gzip_level` | `--gzip-level <1..12>` | `6` | Compression level (`1..=12` with `libdeflate`, `1..=9` with `flate2`). **Implication:** `6` is fastest; `9` trims an extra **~5–8%** off final archive size with minimal wall-clock cost on multi-core CPUs. |
| `terrain.resume` | `--resume` / `--no-resume` | `false` | Resumes an interrupted build from `.tin_checkpoint.bin` with zero recomputation. Safe after `Ctrl-C` or power loss. |

---

### Section `[tiles3d]` — OGC 3D Tiles 1.1 Pyramid (`cesium-tiler build3dtiles`)

| `cesium-tiler.toml` Key | CLI Override Flag(s) | Default | Implications & Tuning Guidance |
|---|---|---|---|
| *(CLI only)* | `-i, --input <PATH>...` | *(required)* | One or more vector files or folders (`.gpkg`, `.parquet`, `.fgb`, `.geojson`, `.shp`). |
| *(CLI only)* | `--bbox "w,s,e,n"` | full extent | Optional WGS84 (`EPSG:4326`) geographic clip box to extract a single city/region quickly. |
| `tiles3d.leaf_zoom` | `--leaf-zoom <Z>` | `14` | Quadtree leaf zoom level (~2.2 km × 1.6 km tiles at mid-latitudes). **Implication:** lower values produce fewer, heavier `.glb` files; higher values produce more HTTP requests. `14` is optimal for city-to-national scale. |
| `tiles3d.lod_levels` | `--lod-levels <N>` | `3` | Number of additive multi-LOD levels (`refine: "ADD"`, default `z = 12..14`). **Implication:** prevents loading millions of small houses when zoomed out while guaranteeing zero geometry duplication. |
| `tiles3d.skirt_depth` | `--skirt-depth <METERS>` | `2.5` | Foundation wall depth extruded below ground elevation. **Implication:** prevents buildings from appearing to float on steep mountain slopes or across TIN simplification errors. |
| `tiles3d.vertical_datum` | `--vertical-datum <wgs84\|preserve>` | `"wgs84"` | Must match your terrain pyramid's `vertical_datum` so buildings sit flush on the terrain surface. |
| `tiles3d.vertical_shift` | `--vertical-shift <METERS>` | `0.0` | Constant vertical offset added to all 3D objects. |
| `tiles3d.gzip` | `--no-gzip` / `--gzip` | `true` | Gzip-compresses `.glb` tiles and external `sub/*.json` tilesets (~3× smaller archives). |
| `tiles3d.buildings_only` | `--buildings-only` / `--include-extra` | `false` | When `true`, only extrudes buildings and tanks (skips 3D lattice towers/pylons, bridges/dams, and sports fields for smaller/faster builds). |
| *(CLI only)* | `--dem <PATH>` | none | Optional DEM source used to drape 2D layers without Z coordinates (e.g. `zone_de_vegetation`, sports fields): accepts any GDAL raster/VRT **or** a `quantized-mesh` `.sqlite` / `.mbtiles` terrain pyramid built by `cesium-tiler build`. |

---

### Section `[imagery]` — Orthoimagery Pyramid (`cesium-tiler build-imagery`)

| `cesium-tiler.toml` Key | CLI Override Flag(s) | Default | Implications & Tuning Guidance |
|---|---|---|---|
| *(CLI only)* | `-i, --input <PATH>...` | *(required)* | One or more orthoimagery files or directories (`.tif`, `.tiff`, `.jp2`, `.vrt`, COG, ECW/SID if supported by GDAL). Coarser layers are automatically stacked beneath finer layers in multi-resolution VRTs. |
| *(CLI only)* | `--source-srs <SRS>` | auto | Overrides source CRS (e.g. `"EPSG:2154"`) for imagery lacking embedded projection metadata. |
| `imagery.tile_format` | `--tile-format <webp\|jpeg\|png>` | `"webp"` | **`webp`** (recommended): ~30–40% smaller than JPEG + full alpha transparency for dataset borders, native in CesiumJS & all modern browsers. **`jpeg`**: universal opaque RGB (no transparency). **`png`**: lossless RGBA (~4×–8× larger). |
| `imagery.quality` | `--quality <1..100>` | `82` | Lossy compression quality for WebP/JPEG (ignored for PNG). **`75–82`** gives crisp aerial detail at minimal disk cost; **`85–92`** is archival quality (~1.5×–2× larger). |
| `imagery.scheme` | `--scheme <webmercator\|geodetic>` | `"webmercator"` | **`webmercator`** (`EPSG:3857`): standard MBTiles 1.3 / Slippy TMS grid (`2^z × 2^z`). **`geodetic`** (`EPSG:4326`): 1:1 Cesium geodetic grid (`2^(z+1) × 2^z`) matching `quantized-mesh-1.0`. |
| `imagery.min_zoom` | `--min-zoom <Z>` | `0` | Coarsest zoom level generated (`0` recommended for full globe zoom-out). |
| `imagery.max_zoom` | `--max-zoom <Z>` | `0` (auto) | Finest zoom level (`0` = computed automatically from source pixel resolution). **Major implication:** each `+1` zoom multiplies tile count and disk size by **~4×** (`z=15` ≈ 4.8 m/px; `z=17` ≈ 1.2 m/px; `z=18` ≈ 0.6 m/px; `z=19` ≈ 0.3 m/px). |
| `imagery.tile_size` | `--tile-size <256\|512>` | `256` | Tile edge size in pixels (`256` standard; `512` hi-DPI reduces request count 4× with 4× larger tiles). |
| `imagery.nodata_black` | `--nodata-black` / `--no-nodata-black` | `false` | Treats exact pure-black RGB `(0, 0, 0)` pixels as transparent NoData collars (useful for legacy ortho tiles without an alpha/mask band). |

> **Note utilisateur — JPEG 2000 / IGN BD ORTHO® : fiabilité avant vitesse.**
>
> `build-imagery` lit les `.jp2` sur GPU via **NVIDIA `nvJPEG2000`** (`libnvjpeg2k.so.0` + `libcudart.so` chargées dynamiquement via `dlopen` lorsque disponibles, pour les fenêtres `≤ 4096×4096`), et bascule sinon sur le driver GDAL `JP2OpenJPEG` (`libopenjp2`) en lecture directe sans VRT global : chaque thread garde au plus 12 datasets ouverts et lit à résolution 1:1 pour utiliser les overviews wavelet intégrées. Côté encodage, `--tile-format webp` appelle directement `libwebp` via `dlopen` (`method = 1`, import `RGBX`/`RGBA` sans `/vsimem/`), avec repli automatique sur GDAL. Le parallélisme vient des threads Rust, **jamais** des pools internes du codec.
>
> - **Gardez `OPJ_NUM_THREADS=0`** (`0` = désactive le pool OpenJPEG ; `1` = pool d’un thread, donc risque de corruption heap sous charge). Le binaire pose déjà `OPJ_NUM_THREADS=0`, `GDAL_NUM_THREADS=1`, `VRT_NUM_THREADS=1` et `JP2OPENJPEG_USE_THREADED_IO=NO` si vous ne les définissez pas ; ne les surchargez pas avec `ALL_CPUS`.
> - **Sans GPU NVIDIA / `nvJPEG2000`**, tous les `.jp2` passent par le driver GDAL `JP2OpenJPEG` (`gdalinfo --formats`). Vérifiez la présence de `libnvjpeg2k.so.0` + `libcudart.so` si vous attendez un décodage GPU.
> - **Dimensionnement** : `--gdal-readers 4..8` pour saturer le NVMe, avec `--workers` réduit en conséquence (par exemple 16/8 sur 24 cœurs). `GDAL_CACHEMAX=1024..2048` suffit ; 8192 n’accélère pas le décodage. Si OpenJPEG continue de planter, **descendre jusqu’à `--gdal-readers 1`** : `script/relaunch_imagery.sh` le fait automatiquement (8 → 4 → 2 → 1 après 3/6/9 crashes).
> - **`--resume` est O(1)** depuis l’ajout du checkpoint `<work_dir>/.imagery_checkpoint.bin` : le FIFO Morton est restauré directement, sans redécoder toutes les tuiles z=14. Sans ce fichier (run démarré avant la mise à jour, ou paramètres modifiés), le tiler retombe sur l’ancienne détection O(N) par scan MBTiles — compatibilité conservée. Ne supprimez pas ce fichier pendant un build.
> - **Pour un run sans surveillance**, lancez `./script/relaunch_imagery.sh` : il vérifie que le schéma MBTiles est lisible avant chaque reprise (l’ouverture SQLite récupère le WAL ; un `quick_check` complet prendre >15 min sur un archive de 150 Gio et est laissé à une vérification manuelle), détecte l’absence de progrès, dégrade automatiquement le nombre de lecteurs et ne s’arrête que sur une fin propre (code 0 + ligne `Imagery pyramid complete` + metadata MBTiles).

---

### Mapbox-Style Vector Pyramids (`cesium-tiler build-vector`)

Converts any OGR-readable vector datasets (`.shp`, `.gpkg`, `.fgb`, `.geojson`, `.parquet`) or native `.osm.pbf` extracts ([`cesium-osm`](crates/cesium-osm/)) into a **styled transparent 256×256 RGBA WebP/PNG pyramid** (`--tile-format webp` [default] / `png`) or a **Mapbox-style MVT pyramid** (`--tile-format mvt` `.pbf`) ready for `cesium-viewer --imagery` or `cesium-export`.

| CLI Flag | Default | Implications & Tuning Guidance |
|---|---|---|
| `-i, --input <PATH>...` | optional with `--style` | One or more vector files (`.shp`, `.gpkg`, `.fgb`, `.geojson`, `.parquet`, `.osm.pbf`) or directories, searched recursively and reprojected to `EPSG:4326` / WebMercator on the fly. |
| `--style <STYLE.json>` | none | Mapbox/MapLibre GL Style v8 JSON (`version`, `name`, `sources`, `layers` with `type`: `fill`/`line`/`circle`, `source-layer`, `minzoom`/`maxzoom`, `filter`, and `paint`). |
| `-o, --output <PATH>` | `[paths].output_dir/vector.*` | `.mbtiles`/`.sqlite` for `--format sqlite` (default); a directory for `--format dir`. |
| `--format <sqlite\|dir>` | auto | `sqlite` writes an MBTiles container (`tiles` + `metadata` including `vector_layers` TileJSON and embedded `style`); `dir` writes `{z}/{x}/{y}.{pbf\|png}`. |
| `--tile-format <webp\|png\|mvt>` | `webp` | `webp` (smallest footprint) and `png` pre-render transparent 256×256 RGBA tiles from the Mapbox `paint`/`layout` rules; `mvt` encodes Mapbox Vector Tiles v2.1 (points, lines, polygons). |
| `--quality <1..=100>` | `55` | WebP encoding quality for `--tile-format webp` (55 gives ~2× smaller tiles than 85 on flat vector overlays). |
| `--layer <NAME>` | `"features"` | Default `source-layer` name when `--style` is not provided. |
| `--bbox <W,S,E,N>` | full extent | Geographic clip in EPSG:4326 degrees, e.g. `--bbox 2.25,48.80,2.40,48.95`. |
| `--min-zoom <Z>` / `--max-zoom <Z>` | `8` / `14` | Pyramid zoom range. |
| `--simplification <F>` | `1.0` | Tile-space vertex deduplication/simplification threshold in `0..=4096` MVT units. |
| `--max-tile-size <BYTES>` | `2000000` | Encoded MVT tile size cap in bytes. |
| `--gzip` / `--no-gzip` | `true` | Gzip-compresses `.pbf` MVT tiles via `libdeflate` (`Content-Encoding: gzip`). |
| `--attributes <A,B,...>` | all (max 16) | Comma-separated attribute allowlist to include in MVT tiles. |
| `--workers <N>` | config `workers` | Rayon worker threads for parallel clipping, encoding/rendering, and compression. |

Example `style.json` (Mapbox GL Style v8 subset):
```json
{
  "version": 8,
  "name": "France Vector Layers",
  "sources": {
    "bdtopo": { "type": "vector", "tiles": ["./data/routes.fgb", "./data/hydro.shp"] }
  },
  "layers": [
    {
      "id": "major-roads",
      "type": "line",
      "source": "bdtopo",
      "source-layer": "routes",
      "minzoom": 8,
      "maxzoom": 14,
      "filter": ["in", "nature", "Autoroute", "Nationale"],
      "paint": { "line-color": "#f59e0b", "line-width": 2.0, "line-opacity": 0.9 }
    }
  ]
}
```

---

### Section `[server]` — Standalone Test & Visualization Server (`cesium-viewer`)

*(Dedicated standalone executable with zero GDAL and zero system SQLite dependencies — auto-loads `[server]` from `./cesium-tiler.toml` unless `--no-config` is passed.)*

| `cesium-tiler.toml` Key | CLI Override Flag(s) | Default | Implications & Tuning Guidance |
|---|---|---|---|
| *(CLI only)* | `<PATH>` | *(required)* | Terrain directory or `.sqlite` / `.mbtiles` archive to serve at `/tiles/`. |
| `server.tiles3d` (repeatable line) | `--tiles3d NAME=PATH` (repeatable) | none | Optional OGC 3D Tiles 1.1 directory or `.sqlite` archive served simultaneously at `/tiles3d/{name}/tileset.json`. The CLI accepts a plain `PATH` (name = file/directory stem) or an explicit `NAME=PATH`; names must be unique. Multiple sources (e.g. buildings + other 3D Tiles) get independent viewer toggles. |
| `server.imagery` | `--imagery <PATH>` | `""` | Optional local offline orthoimagery MBTiles/SQLite archive or TMS directory served at `/imagery/` and automatically selected as the default CesiumJS basemap. |
| *(CLI only)* | `--geocoder <PATH>` | none | Optional offline address SQLite DB (`format=cesium-geocoder`, built by [`script/geocoder`](script/README.md)). Enables the viewer search bar (`/api/geocode`) and click-to-address reverse lookup (`/api/reverse`). |
| *(CLI only)* | `-c, --config <PATH>` / `--no-config` | `./cesium-tiler.toml` (auto) | Load a specific `cesium-tiler.toml` or ignore `./cesium-tiler.toml`. |
| `server.host` | `--host <ADDR>` | `"127.0.0.1"` | Bind address (`"127.0.0.1"` = local machine only; `"0.0.0.0"` = accessible on your LAN). |
| `server.port` | `-p, --port <PORT>` | `8080` | TCP listening port for both the tile API and the embedded CesiumJS viewer (`http://<host>:<port>/`). |
| `server.wms_url` | `--wms-url <URL>` | `""` | Custom WMS base imagery endpoint added to the embedded CesiumJS viewer (default viewer provides global EOX Sentinel-2, Esri World Imagery, and OpenStreetMap). |
| `server.wms_layer` | `--wms-layer <LAYER>` | `""` | WMS layer name paired with `wms_url`. |

The browser reads `/viewer-config.json` (`terrain`, `tilesets3d`, imagery/WMS settings, `hasGeocoder`). `window.cesiumViewer` is exposed for automation/debugging.

---

### Standalone Exporter (`cesium-export`) — Zero GDAL / Zero System SQLite

`cesium-export` unpacks any terrain (`quantized-mesh-1.0`), OGC 3D Tiles 1.1, orthoimagery MBTiles 1.3, or offline geocoder `.sqlite`/`.mbtiles` archive into physical static files on any bare machine (no GDAL, no SQLite, no GPU required):

| CLI Flag | Default | Implications & Tuning Guidance |
|---|---|---|
| `-i, --input <SQLITE>` | *(required)* | Input `.sqlite` / `.mbtiles` archive (auto-detects terrain, 3D Tiles 1.1, WebP/JPEG/PNG imagery, or `format=cesium-geocoder`). |
| `-o, --output <DIR>` | *(required)* | Destination folder for `{z}/{x}/{y}.{terrain\|glb\|webp\|jpg\|png}` + `layer.json` / `tileset.json` / `tilemapresource.xml` / `WMTSCapabilities.xml` / `tilejson.json` / `geocoder.json`. |
| `--min-zoom <Z>` / `--max-zoom <Z>` | all | Optional zoom range filter (e.g. export only `z = 0..14` for a preview server). |
| `--gunzip` | `false` | Decompress gzipped terrain/3D Tiles during export (ignored for imagery; increases terrain disk usage ~3×). |
| `--service tms\|wmts\|xyz` | `tms` | Imagery only. **TMS** keeps the MBTiles bottom-up rows and writes a complete `tilemapresource.xml` (`global-mercator`/`global-geodetic`, `Origin`, `TileSets`) — the Cesium-ready default. **WMTS** flips to top-down rows and writes `WMTSCapabilities.xml` with RESTful `ResourceURL` templates. **XYZ** flips to top-down rows and writes `tilejson.json` for `UrlTemplateImageryProvider`. |
| `--wmts-base-url <URL>` | `.` | Public base URL written into the WMTS `GetCapabilities` / `ResourceURL` (use the final HTTPS URL behind your reverse proxy). |
| `--to-postgis <FILE.sql>` | — | For `cesium-geocoder` archives: write a standalone PostGIS dump (`geometry(Point,4326)` + GiST + `tsvector`/GIN + `COPY ... FROM STDIN`). |
| `--to-mysql <FILE.sql[.gz]>` | — | For `cesium-geocoder` archives: write a MySQL 8+ / MariaDB 10.6+ SQL dump (`POINT` SRID 4326 + `SPATIAL` + `FULLTEXT`), auto-gzipped if ending in `.gz`. |
| `--web-config` | `false` | Writes ready-to-use Apache (`.htaccess`) and Nginx (`nginx_terrain.conf` / `nginx_3dtiles.conf` / `nginx_imagery.conf` / `nginx_geocoder.conf`) configs in the output directory. |
| `--workers <N>` | `cores - 2` | Parallel filesystem writer threads (~40,000 tiles/s on NVMe). |
| `--resume` | `false` | Skips tiles that already exist on disk (safe resume after `Ctrl-C`). |
| `--no-db-copy` | `false` | For geocoder: skip copying `addresses.sqlite` next to `geocoder.json`. |

Imagery is **never transcoded**: the MIME type and file extension always come from `metadata.format`, so a WebP pyramid stays WebP in `tilemapresource.xml`, `WMTSCapabilities.xml`, and `tilejson.json`. To obtain JPEG, build the pyramid with `build-imagery --tile-format jpeg`.

For geocoder archives the exporter writes `geocoder.json` (count, bounds, source metadata), copies `addresses.sqlite` unless `--no-db-copy`, and can emit a PostGIS SQL dump with `--to-postgis` or MySQL/MariaDB SQL with `--to-mysql`. The PostGIS table uses WGS84 points (`SRID=4326`), a GiST spatial index and a French `tsvector` GIN index equivalent to the SQLite FTS5 index.

---

### Additional `cesium-tiler` Utility Subcommands

| Subcommand | Key Flags | Purpose |
|---|---|---|
| **`cesium-tiler init`** | `-o <PATH>`, `--profile <workstation\|balanced\|dedicated>`, `-y/--non-interactive` | Inspects host hardware (CPU, RAM, GPUs, disk, geoids) and interactively generates a didactic `cesium-tiler.toml`. |
| **`cesium-tiler build-vector`** | `-i <SHP\|GPKG\|FGB...>`, `--style <STYLE.json>`, `-o <MBTILES>`, `--tile-format <webp\|png\|mvt>`, `--quality <1..=100>`, `--layer`, `--bbox`, `--min-zoom/--max-zoom`, `--simplification`, `--attributes`, `--format`, `--gzip/--no-gzip` | Builds a Mapbox-style WebP/PNG raster or MVT vector pyramid (see dedicated section above; `--quality` defaults to `55` for vector overlays, independent of `build-imagery` ortho `--quality`). |
| **`cesium-tiler inspect`** | `<FILE \| SQLITE>`, `--tile z/x/y` | Decodes a `.terrain` file (or SQLite entry) and prints ECEF header, height range, Horizon Occlusion Point, vertex/triangle counts, normals, watermask, and Extension 4 metadata. |
| **`cesium-tiler repair-roots`** | `<SQLITE>` | Repairs low-zoom (`z <= 5`) root tiles in-place (< 1 s) for legacy archives so CesiumJS 3D mode renders the globe immediately. |
| **`cesium-tiler generate-test-dem`** | `-o <TIF>`, `--west/--south/--east/--north`, `--width/--height` | Generates a synthetic alpine GeoTIFF DEM for zero-download testing and benchmarking. |
| **`cesium-tiler info`** | *(none)* | Prints the full hardware & environment report (CPU, RAM, detected `wgpu` GPUs, GDAL version, free disk space, local geoids). |

---

## Prebuilt Binaries & Building from Source

Every `v*` git tag triggers [`.github/workflows/release.yml`](.github/workflows/release.yml) to publish 6 platform archives (each containing **`cesium-tiler`**, **`cesium-export`**, and **`cesium-viewer`**) + `SHA256SUMS.txt`:

| Platform | Architecture | Archive | Runtime Dependencies |
|---|---|---|---|
| **Linux** | `x86_64` | `cesiumjs-gdal-gpu-tiler-<tag>-linux-x86_64.tar.gz` | `cesium-tiler`: `libgdal`, `libdeflate` · **`cesium-export` & `cesium-viewer`: none** |
| **Linux** | `ARM64` (`aarch64`) | `cesiumjs-gdal-gpu-tiler-<tag>-linux-arm64.tar.gz` | `cesium-tiler`: `libgdal`, `libdeflate` · **`cesium-export` & `cesium-viewer`: none** |
| **macOS** | Apple Silicon (`ARM64`) | `cesiumjs-gdal-gpu-tiler-<tag>-macos-arm64.tar.gz` | `cesium-tiler`: `brew install gdal libdeflate` · **`cesium-export` & `cesium-viewer`: none** |
| **macOS** | Intel (`x86_64`) | `cesiumjs-gdal-gpu-tiler-<tag>-macos-x86_64.tar.gz` | `cesium-tiler`: `brew install gdal libdeflate` · **`cesium-export` & `cesium-viewer`: none** |
| **Windows** | `x86_64` | `cesiumjs-gdal-gpu-tiler-<tag>-windows-x86_64.zip` | Self-contained (GDAL/PROJ/libdeflate DLLs bundled) |
| **Windows** | `ARM64` | `cesiumjs-gdal-gpu-tiler-<tag>-windows-arm64.zip` | Self-contained (GDAL/PROJ DLLs bundled) |

### Building from Source
```bash
# Build all three binaries (cesium-tiler, cesium-export, cesium-viewer)
cargo build --release --workspace

# Build ONLY the zero-dependency exporter or test server (does NOT require GDAL!)
cargo build --release -p cesium-export
cargo build --release -p cesium-viewer

# Optional: build cesium-tiler without system libdeflate (pure-Rust flate2 fallback)
cargo build --release -p cesium-tiler --no-default-features

# Run the full workspace test suite
cargo test --workspace
```

---

## Optional Enrichment & Audit Scripts (`script/`)

The `script/` folder provides **optional** Rust companion tools that complement the 4 core executables without adding any dependencies to them (standalone crates outside the root workspace, except `enrich-3dtiles-premium` which links GDAL; prebuilt binaries are also bundled under `script/` in GitHub Releases):

| Tool | Purpose | Key Usage |
|---|---|---|
| **`build-geocoder`** | Builds an offline FTS5 + R*Tree SQLite database (`addresses.sqlite`) from GeoParquet (any WKB geometry), CSV, or GeoJSON (addresses + toponyms/hydrography) for `cesium-viewer --geocoder` | `build-geocoder -i adresse_ban.parquet -o output/addresses.sqlite` |
| **`enrich-3dtiles-addresses`** | Bakes an `address` property into OGC 3D Tiles 1.1 `.glb` buildings by fast 3D spatial proximity against `addresses.sqlite` | `enrich-3dtiles-addresses -i output/buildings.sqlite -g output/addresses.sqlite` |
| **`enrich-3dtiles-rnb`** | Enriches 3D Tiles buildings using BD TOPO 2026 (`batiment.parquet`, RNB IDs, `lien_adresse_vers_bdtopo.parquet`, plus optional `--geocoder` spatial fallback) in a single pass | `enrich-3dtiles-rnb -i output/buildings.sqlite --batiment batiment.parquet` |
| **`enrich-3dtiles-premium`** | Enriches 3D Tiles buildings using explicit IGN `ADRESSE-PREMIUM` link tables (`A_ADR-PARC`, `B_ADR-BATI`, `C_BATI-PARC`) | `enrich-3dtiles-premium -i output/buildings.sqlite --adresses-ban ...` |
| **`audit-archives`** | Inspects `.sqlite` / `.mbtiles` archives (auto-detects profile, zoom pyramid, empty tiles, GLB property coverage, optional `--verify-magic` & `--deep`) | `audit-archives -i output/*.sqlite --verify-magic` |
| **`prep-parcellaire`** | Consolidates/filters departmental `PARCELLAIRE-EXPRESS` shapefiles (`--mode symlinks`, `gpkg`, or `parquet`) for `cesium-tiler build-vector` / `build-geocoder` | `prep-parcellaire -i .../extrait -o output/parc_d05 --dept 05` |

See **[script/README.md](script/README.md)** for compilation instructions, full CLI flags, and end-to-end examples.

---

## Full Documentation

| Document | Audience | Contents |
|---|---|---|
| **[User Guide & API Reference](docs/USER_GUIDE.md)** | Users & Integrators | Step-by-step workflows, `cesium-tiler init` & `cesium-tiler.toml` guide, geoid setup, **Rust library API (`cesium-tiler-core`)**, **HTTP/REST API**, **CesiumJS integration snippet**, and **Apache/Nginx deployment** |
| **[Developer & Algorithms Guide](docs/DEVELOPER_GUIDE.md)** | Contributors & Engineers | Deep-dive into every algorithm (2nd-order filter, RTIN/LEB, 4 WGSL shaders, VRAM ping-pong, Morton FIFO, WGS84/HOP, scanline watermask, 3D Tiles 1.1 earcut/roofs/glTF, multi-res VRT, Keep-Alive server) + full codebase map |
| **[Geospatial Data Catalog](docs/DATA_CATALOG.md)** | GIS / Data Engineers | Supported raster/vector formats, multi-resolution VRT stacking, external PROJ geoid grids, `VectorFieldMap` schema aliases, NoData sentinels, and SQLite archive schemas |
| **[Optional Enrichment Scripts](script/README.md)** | Data Enrichment Users | Optional Rust utilities in `script/`: `build-geocoder`, `enrich-3dtiles-addresses`, `enrich-3dtiles-rnb`, `enrich-3dtiles-premium`, `audit-archives`, and `prep-parcellaire` |

### Generating HTML API Documentation (`rustdoc` / Javadoc Equivalent)
Rust ships with `cargo doc` (`rustdoc`), which compiles every `///` and `//!` documentation comment in the workspace into a searchable, cross-linked HTML reference site:

```bash
# Generate and open the full HTML API documentation in your browser
cargo doc --workspace --no-deps --open

# Include internal/private module documentation as well
cargo doc --workspace --no-deps --document-private-items --open
```

The generated site is written to `target/doc/cesium_tiler_core/index.html` (and verified warning-free in CI via `RUSTDOCFLAGS="-D warnings" cargo doc --workspace --no-deps`).

---

## License

Dual-licensed under **MIT** or **Apache-2.0**, at your option.