@nexgen-os/grb 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nexgen OS contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,72 @@
1
- # Temporary Holding Version
1
+ # `@nexgen-os/grb` — the buildings of a place in Flanders, from open data
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Two open services of Digitaal Vlaanderen describe what is built in Flanders.
4
+ The Large-scale Reference Database (GRB) draws every building on the ground
5
+ (layer `GBG`), each with a persistent object id; the Digital Height Model of
6
+ Flanders II (DHM Vlaanderen II) gives, at 1 m, the surface the airborne laser
7
+ saw — roofs and trees — and the terrain under it. This connector reads both
8
+ and answers a CityJSON model in Belgian Lambert 72 (EPSG:31370) that the
9
+ `building` module imports as the buildings of a participant. MIT; open, no
10
+ key. Sources `grb` and `dhmv`, shipped with the package (`sources.json`).
11
+
12
+ ```ts
13
+ import { registerSource } from '@nexgen-os/core';
14
+ import { grbSources, siteModel } from '@nexgen-os/grb';
15
+ import { importCityJson } from './modules/building/src/index.js'; // the building module
16
+
17
+ for (const row of grbSources) await registerSource(db, row);
18
+ const model = await siteModel({ lon: 3.72125, lat: 51.05494, radiusM: 30 });
19
+ await importCityJson(db, { participantId }, model, { sourceCode: 'grb', use: 'residential' });
20
+ ```
21
+
22
+ Each building lands with:
23
+
24
+ | What | From |
25
+ |---|---|
26
+ | footprint, in WGS 84 | the GRB polygon, every hole kept |
27
+ | `elevation_m` | the median of the terrain model under the footprint, above the Ostend datum (TAW) |
28
+ | `height_m` | the ridge above that ground |
29
+ | `global_id` | `GRB.GBG.<OIDN>`, the persistent object id, the same across versions of the building |
30
+ | `metadata.cityjson.attributes.grb` | the version (`UIDN`), the type GRB gives (`hoofdgebouw`, `bijgebouw`…), the dates of the version and of the survey |
31
+ | `metadata.cityjson.attributes.heights` | ground, eave and ridge, the cells they were read from and the percentiles used |
32
+
33
+ ## The heights of a footprint
34
+
35
+ `heightsInFootprint(polygons, surface, terrain, percentiles)` reads the cells
36
+ of both models whose centre lies inside the footprint and where both have a
37
+ value: the ground is the median of the terrain, the eave and the ridge two
38
+ percentiles of the surface, each above that ground, linear between cells.
39
+ The percentiles are data (`{ eave: 10, ridge: 99 }` by default): the 99th
40
+ keeps a chimney or an antenna from raising the ridge, the 10th keeps the
41
+ cells of a gutter overhanging the street out of the eave. A footprint the
42
+ grid does not cover keeps no height and is listed in `skipped`.
43
+
44
+ What the model does not say: the shape of the roof (no faces are written;
45
+ `building.surfaces` waits for a roof model or a survey), a tree over a roof
46
+ (it counts as roof), and a building built or demolished after the laser
47
+ flight (DHM Vlaanderen II was flown in 2013–2015) — `grb.survey_date` and the
48
+ heights then disagree, and the heights are the ones to check.
49
+
50
+ ## The pieces
51
+
52
+ - `grb({ fetch?, baseUrl?, limit? }).buildings({ lon, lat, radiusM })` — the
53
+ GRB footprints whose outline meets the box around the point; refuses
54
+ `too_many_buildings` past `limit` (500) rather than return part of a place.
55
+ - `dhmv({ fetch?, baseUrl?, maxCells? }).grid('surface' | 'terrain', box)` —
56
+ one model over a box in Lambert 72, as a `Raster`; refuses `area_too_large`
57
+ past 4 000 000 cells.
58
+ - `readGeoTiff(bytes)` — the TIFF of a coverage answer (the second part of
59
+ the multipart answer of WCS 2.0, or a plain file): one band of uncompressed
60
+ 32-bit floats, in strips or tiles, either byte order, placed by its pixel
61
+ scale and tie point, no-data as `NaN`; anything else is refused
62
+ `tiff_unsupported`.
63
+ - `siteModel(area, { percentiles?, fetch? })` — all of it, as a `CityModel`.
64
+
65
+ Refusals by name: `radius_required`, `too_many_buildings`, `area_too_large`,
66
+ `grb_unavailable`, `dhmv_unavailable`, `grid_mismatch`, `tiff_not_found`,
67
+ `tiff_unsupported`.
68
+
69
+ Licence of the data: Modellicentie Gratis Hergebruik, attribution « © Digitaal
70
+ Vlaanderen — GRB » and « © Digitaal Vlaanderen — DHM Vlaanderen II ». The
71
+ recorded answers under `tests/fixtures` are two buildings of a street in
72
+ Ghent and the two models over their box, kept under the same licence.
@@ -0,0 +1,22 @@
1
+ /** A grid of values, north-up: cell (col, row) covers x0 + col·dx … and y0 − row·dy …, row 0 at the top. */
2
+ export interface Raster {
3
+ /** The x of the west edge of the grid, in the coverage's reference system. */
4
+ x0: number;
5
+ /** The y of the north edge of the grid. */
6
+ y0: number;
7
+ /** The width of a cell along x. */
8
+ dx: number;
9
+ /** The height of a cell along y, positive. */
10
+ dy: number;
11
+ width: number;
12
+ height: number;
13
+ /** Row by row from the north, `NaN` where the coverage has no value. */
14
+ values: Float32Array;
15
+ }
16
+ /**
17
+ * The first TIFF in `bytes` — a file, or the `multipart/related` answer of a
18
+ * WCS 2.0 GetCoverage whose second part is the TIFF — as a `Raster`. Refuses
19
+ * `tiff_not_found` without one and `tiff_unsupported` for anything but one
20
+ * band of uncompressed 32-bit floats placed by a pixel scale and a tie point.
21
+ */
22
+ export declare function readGeoTiff(bytes: Uint8Array): Raster;
@@ -0,0 +1,106 @@
1
+ // A GeoTIFF of one band of 32-bit floats, uncompressed, in strips or tiles:
2
+ // what a Web Coverage Service gives for a height model. Enough to read it,
3
+ // nothing more; any other TIFF is refused by name.
4
+ const TAG = {
5
+ width: 256, height: 257, bitsPerSample: 258, compression: 259, stripOffsets: 273, samplesPerPixel: 277,
6
+ rowsPerStrip: 278, tileWidth: 322, tileLength: 323, tileOffsets: 324, sampleFormat: 339,
7
+ pixelScale: 33550, tiepoint: 33922, nodata: 42113,
8
+ };
9
+ const SIZE = { 1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 6: 1, 7: 1, 8: 2, 9: 4, 10: 8, 11: 4, 12: 8, 16: 8 };
10
+ /**
11
+ * The first TIFF in `bytes` — a file, or the `multipart/related` answer of a
12
+ * WCS 2.0 GetCoverage whose second part is the TIFF — as a `Raster`. Refuses
13
+ * `tiff_not_found` without one and `tiff_unsupported` for anything but one
14
+ * band of uncompressed 32-bit floats placed by a pixel scale and a tie point.
15
+ */
16
+ export function readGeoTiff(bytes) {
17
+ const start = findTiff(bytes);
18
+ if (start < 0)
19
+ throw new Error('tiff_not_found: the answer holds no TIFF');
20
+ const view = new DataView(bytes.buffer, bytes.byteOffset + start, bytes.byteLength - start);
21
+ const little = view.getUint8(0) === 0x49;
22
+ if (view.getUint16(2, little) !== 42)
23
+ throw new Error('tiff_unsupported: BigTIFF or not a TIFF');
24
+ const ifd = view.getUint32(4, little);
25
+ const count = view.getUint16(ifd, little);
26
+ const tags = new Map();
27
+ const strings = new Map();
28
+ for (let i = 0; i < count; i += 1) {
29
+ const at = ifd + 2 + 12 * i;
30
+ const tag = view.getUint16(at, little);
31
+ const type = view.getUint16(at + 2, little);
32
+ const n = view.getUint32(at + 4, little);
33
+ const size = (SIZE[type] ?? 1) * n;
34
+ const offset = size <= 4 ? at + 8 : view.getUint32(at + 8, little);
35
+ if (type === 2) {
36
+ strings.set(tag, new TextDecoder().decode(new Uint8Array(view.buffer, view.byteOffset + offset, n)).replace(/\0+$/, ''));
37
+ continue;
38
+ }
39
+ const values = [];
40
+ for (let k = 0; k < n; k += 1) {
41
+ const p = offset + k * (SIZE[type] ?? 1);
42
+ values.push(type === 3 ? view.getUint16(p, little) : type === 4 ? view.getUint32(p, little)
43
+ : type === 12 ? view.getFloat64(p, little) : type === 11 ? view.getFloat32(p, little) : view.getUint8(p));
44
+ }
45
+ tags.set(tag, values);
46
+ }
47
+ const one = (tag, fallback) => {
48
+ const v = tags.get(tag)?.[0] ?? fallback;
49
+ if (v === undefined)
50
+ throw new Error(`tiff_unsupported: tag ${tag} missing`);
51
+ return v;
52
+ };
53
+ if (one(TAG.compression, 1) !== 1)
54
+ throw new Error('tiff_unsupported: compressed');
55
+ if (one(TAG.samplesPerPixel, 1) !== 1)
56
+ throw new Error('tiff_unsupported: more than one band');
57
+ if (one(TAG.bitsPerSample) !== 32 || one(TAG.sampleFormat, 1) !== 3)
58
+ throw new Error('tiff_unsupported: not 32-bit floats');
59
+ const scale = tags.get(TAG.pixelScale);
60
+ const tie = tags.get(TAG.tiepoint);
61
+ if (!scale || !tie)
62
+ throw new Error('tiff_unsupported: not placed by a pixel scale and a tie point');
63
+ const width = one(TAG.width);
64
+ const height = one(TAG.height);
65
+ const nodataText = strings.get(TAG.nodata);
66
+ const nodata = nodataText !== undefined && nodataText.trim() !== '' ? Number(nodataText) : null;
67
+ const values = new Float32Array(width * height).fill(Number.NaN);
68
+ const put = (col, row, p) => {
69
+ const v = view.getFloat32(p, little);
70
+ values[row * width + col] = nodata !== null && v === nodata ? Number.NaN : v;
71
+ };
72
+ if (tags.has(TAG.tileOffsets)) {
73
+ const tw = one(TAG.tileWidth);
74
+ const th = one(TAG.tileLength);
75
+ const across = Math.ceil(width / tw);
76
+ tags.get(TAG.tileOffsets).forEach((offset, t) => {
77
+ const c0 = (t % across) * tw;
78
+ const r0 = Math.floor(t / across) * th;
79
+ for (let r = 0; r < th && r0 + r < height; r += 1) {
80
+ for (let c = 0; c < tw && c0 + c < width; c += 1)
81
+ put(c0 + c, r0 + r, offset + 4 * (r * tw + c));
82
+ }
83
+ });
84
+ }
85
+ else {
86
+ const rowsPerStrip = one(TAG.rowsPerStrip, height);
87
+ (tags.get(TAG.stripOffsets) ?? []).forEach((offset, s) => {
88
+ for (let r = 0; r < rowsPerStrip && s * rowsPerStrip + r < height; r += 1) {
89
+ for (let c = 0; c < width; c += 1)
90
+ put(c, s * rowsPerStrip + r, offset + 4 * (r * width + c));
91
+ }
92
+ });
93
+ }
94
+ // The tie point gives the model point of a raster point: (i, j) ↦ (x, y).
95
+ const [i, j, , x, y] = tie;
96
+ return { x0: x - i * scale[0], y0: y + j * scale[1], dx: scale[0], dy: scale[1], width, height, values };
97
+ }
98
+ function findTiff(bytes) {
99
+ for (let i = 0; i + 4 <= bytes.length; i += 1) {
100
+ if (bytes[i] === 0x49 && bytes[i + 1] === 0x49 && bytes[i + 2] === 42 && bytes[i + 3] === 0)
101
+ return i;
102
+ if (bytes[i] === 0x4d && bytes[i + 1] === 0x4d && bytes[i + 2] === 0 && bytes[i + 3] === 42)
103
+ return i;
104
+ }
105
+ return -1;
106
+ }
@@ -0,0 +1,116 @@
1
+ import type { SourceRow } from '@nexgen-os/core';
2
+ import type { CityModel } from '@nexgen-os/cityjson';
3
+ import { type Raster } from './geotiff.js';
4
+ export { readGeoTiff, type Raster } from './geotiff.js';
5
+ /** The reference system of both services: Belgian Lambert 72. */
6
+ export declare const LAMBERT_72 = 31370;
7
+ /** A fetch that can read bytes as well as JSON; the platform's by default. */
8
+ export type BinaryFetch = (url: string) => Promise<{
9
+ ok: boolean;
10
+ status: number;
11
+ json(): Promise<unknown>;
12
+ arrayBuffer(): Promise<ArrayBuffer>;
13
+ }>;
14
+ /** Around a point: WGS 84 longitude and latitude, and a radius in metres. */
15
+ export interface Area {
16
+ lon: number;
17
+ lat: number;
18
+ radiusM: number;
19
+ }
20
+ /** A box in Lambert 72: west, south, east, north, in metres. */
21
+ export type Box = [number, number, number, number];
22
+ /** A polygon in Lambert 72: an outer ring, then its holes, each closed. */
23
+ export type Rings = [number, number][][];
24
+ /** A building on the ground as GRB draws it. */
25
+ export interface GrbBuilding {
26
+ /** The persistent object id (`OIDN`): the same building across its versions. */
27
+ oidn: number;
28
+ /** The id of this version of the object (`UIDN`). */
29
+ uidn: number;
30
+ /** What GRB says it is (`hoofdgebouw`, `bijgebouw`…), as written. */
31
+ type: string;
32
+ /** The date of this version (`VERSDATUM`), `YYYY-MM-DD`. */
33
+ versionDate: string | null;
34
+ /** The date the building was surveyed (`OPNDATUM`), `YYYY-MM-DD`. */
35
+ surveyDate: string | null;
36
+ /** Its footprint: one polygon, or several. */
37
+ polygons: Rings[];
38
+ }
39
+ interface Common {
40
+ fetch?: BinaryFetch;
41
+ }
42
+ /**
43
+ * The buildings of GRB (layer `GRB:GBG` of its Web Feature Service) whose
44
+ * footprint meets the box around a point. Refuses `too_many_buildings` past
45
+ * `limit` (500 by default) rather than return part of the place, and
46
+ * `grb_unavailable` with the status of the service.
47
+ */
48
+ export declare function grb(options?: Common & {
49
+ baseUrl?: string;
50
+ limit?: number;
51
+ }): {
52
+ source_code: string;
53
+ buildings(area: Area): Promise<GrbBuilding[]>;
54
+ };
55
+ /** The two models of DHM Vlaanderen II at 1 m: what the laser saw (`surface`) and the ground under it (`terrain`). */
56
+ export type HeightModel = 'surface' | 'terrain';
57
+ /**
58
+ * DHM Vlaanderen II through its Web Coverage Service: a model over a box in
59
+ * Lambert 72, widened to whole metres, as a raster in metres above the
60
+ * Ostend datum (TAW). Refuses `area_too_large` past `maxCells` cells
61
+ * (4 000 000, a box of 2 km by 2 km) and `dhmv_unavailable` with the
62
+ * status of the service.
63
+ */
64
+ export declare function dhmv(options?: Common & {
65
+ baseUrl?: string;
66
+ maxCells?: number;
67
+ }): {
68
+ source_code: string;
69
+ grid(model: HeightModel, box: Box): Promise<Raster>;
70
+ };
71
+ /** Which share of a roof's cells lie below its eave and its ridge: a model, given as data. */
72
+ export interface RoofPercentiles {
73
+ /** The percentile of the surface model inside the footprint taken as the eave; 10 by default. */
74
+ eave: number;
75
+ /** The percentile taken as the ridge; 99 by default, so that a chimney or an antenna does not raise it. */
76
+ ridge: number;
77
+ }
78
+ export declare const DEFAULT_ROOF_PERCENTILES: RoofPercentiles;
79
+ /** What two height models say of a footprint, in metres. */
80
+ export interface FootprintHeights {
81
+ /** The terrain under the footprint, its median, above the datum of the models. */
82
+ ground: number;
83
+ /** The eave above the ground. */
84
+ eave: number;
85
+ /** The ridge above the ground. */
86
+ ridge: number;
87
+ /** The cells whose centre lies in the footprint, on both models. */
88
+ cells: number;
89
+ }
90
+ /**
91
+ * The ground, eave and ridge of a footprint, from a surface model and a
92
+ * terrain model of the same grid: the median of the terrain under it, and
93
+ * two percentiles (`percentiles`, linear between cells) of the surface over
94
+ * it, each above that ground. A cell counts when its centre lies inside the
95
+ * footprint and both models have a value there. Null when no cell does: a
96
+ * footprint smaller than the grid, or outside it.
97
+ */
98
+ export declare function heightsInFootprint(polygons: Rings[], surface: Raster, terrain: Raster, percentiles?: RoofPercentiles): FootprintHeights | null;
99
+ /** The CityObject id of a GRB building: its persistent object id, never the id of a version. */
100
+ export declare const grbObjectId: (oidn: number) => string;
101
+ /**
102
+ * The buildings around a point as a CityJSON model in Lambert 72, ready for
103
+ * `importCityJson()` of the `building` module: each GRB footprint at the
104
+ * height of its ground, its ridge above the ground as its measured height,
105
+ * and in its attributes its eave and ridge, the cells they were read from,
106
+ * the percentiles used and what GRB says of it. A footprint the height
107
+ * model does not cover keeps no height and is listed in `skipped`.
108
+ */
109
+ export declare function siteModel(area: Area, options?: Common & {
110
+ percentiles?: RoofPercentiles;
111
+ grbUrl?: string;
112
+ dhmvUrl?: string;
113
+ limit?: number;
114
+ }): Promise<CityModel>;
115
+ /** The `sources` rows this package ships (`sources.json`): write each with `registerSource()` of the core. */
116
+ export declare const grbSources: SourceRow[];
package/dist/index.js ADDED
@@ -0,0 +1,225 @@
1
+ // GRB and DHM Vlaanderen — the buildings of a place in Flanders from open
2
+ // data, as a CityJSON model the `building` module imports.
3
+ //
4
+ // The Large-scale Reference Database of Flanders (GRB) draws every building
5
+ // on the ground (`GBG`) with a persistent object id; the Digital Height
6
+ // Model of Flanders II (DHMV II) gives, at 1 m, the surface the laser saw
7
+ // (DSM, roofs and trees) and the terrain under it (DTM). Both are services
8
+ // of Digitaal Vlaanderen, open, without a key. Sources `grb` and `dhmv`,
9
+ // shipped with this package (`sources.json`).
10
+ //
11
+ // grb().buildings(area) the footprints around a point, in Lambert 72 (EPSG:31370)
12
+ // dhmv().grid(model, bbox) the surface or the terrain model over a box, as a raster
13
+ // heightsInFootprint(…) ground, eave and ridge of a footprint from the two rasters
14
+ // siteModel(area) all of it, as a CityModel for `importCityJson()`
15
+ import { readFileSync } from 'node:fs';
16
+ import { readGeoTiff } from './geotiff.js';
17
+ export { readGeoTiff } from './geotiff.js';
18
+ /** The reference system of both services: Belgian Lambert 72. */
19
+ export const LAMBERT_72 = 31370;
20
+ /**
21
+ * The buildings of GRB (layer `GRB:GBG` of its Web Feature Service) whose
22
+ * footprint meets the box around a point. Refuses `too_many_buildings` past
23
+ * `limit` (500 by default) rather than return part of the place, and
24
+ * `grb_unavailable` with the status of the service.
25
+ */
26
+ export function grb(options = {}) {
27
+ const base = (options.baseUrl ?? 'https://geo.api.vlaanderen.be/GRB/wfs').replace(/\/+$/, '');
28
+ const doFetch = options.fetch ?? globalThis.fetch;
29
+ const limit = options.limit ?? 500;
30
+ return {
31
+ source_code: 'grb',
32
+ async buildings(area) {
33
+ const [west, south, east, north] = degreesAround(area);
34
+ const params = new URLSearchParams({
35
+ service: 'WFS', version: '2.0.0', request: 'GetFeature', typeNames: 'GRB:GBG',
36
+ outputFormat: 'application/json', srsName: `EPSG:${LAMBERT_72}`, count: String(limit + 1),
37
+ // WFS 2.0 with a URN reference system: latitude first.
38
+ bbox: `${south},${west},${north},${east},urn:ogc:def:crs:EPSG::4326`,
39
+ });
40
+ const res = await doFetch(`${base}?${params}`);
41
+ if (!res.ok)
42
+ throw new Error(`grb_unavailable: the GRB service answered ${res.status}`);
43
+ const body = (await res.json());
44
+ const features = body.features ?? [];
45
+ if (features.length > limit)
46
+ throw new Error(`too_many_buildings: more than ${limit} buildings around the point; take a smaller radius`);
47
+ return features.filter((f) => f.geometry).map(fromGbg);
48
+ },
49
+ };
50
+ }
51
+ function fromGbg(f) {
52
+ const g = f.geometry;
53
+ return {
54
+ oidn: f.properties.OIDN,
55
+ uidn: f.properties.UIDN,
56
+ type: f.properties.LBLTYPE ?? '',
57
+ versionDate: f.properties.VERSDATUM ?? null,
58
+ surveyDate: f.properties.OPNDATUM ?? null,
59
+ polygons: g.type === 'Polygon' ? [g.coordinates] : g.coordinates,
60
+ };
61
+ }
62
+ const COVERAGES = { surface: 'DHMVII_DSM_1m', terrain: 'DHMVII_DTM_1m' };
63
+ /**
64
+ * DHM Vlaanderen II through its Web Coverage Service: a model over a box in
65
+ * Lambert 72, widened to whole metres, as a raster in metres above the
66
+ * Ostend datum (TAW). Refuses `area_too_large` past `maxCells` cells
67
+ * (4 000 000, a box of 2 km by 2 km) and `dhmv_unavailable` with the
68
+ * status of the service.
69
+ */
70
+ export function dhmv(options = {}) {
71
+ const base = (options.baseUrl ?? 'https://geo.api.vlaanderen.be/DHMV/wcs').replace(/\/+$/, '');
72
+ const doFetch = options.fetch ?? globalThis.fetch;
73
+ const maxCells = options.maxCells ?? 4_000_000;
74
+ return {
75
+ source_code: 'dhmv',
76
+ async grid(model, box) {
77
+ const [w, s, e, n] = [Math.floor(box[0]), Math.floor(box[1]), Math.ceil(box[2]), Math.ceil(box[3])];
78
+ if ((e - w) * (n - s) > maxCells)
79
+ throw new Error(`area_too_large: ${e - w} m by ${n - s} m is more than ${maxCells} cells of the height model`);
80
+ const params = new URLSearchParams({ service: 'WCS', version: '2.0.1', request: 'GetCoverage', CoverageId: COVERAGES[model], format: 'image/tiff' });
81
+ const res = await doFetch(`${base}?${params}&subset=x(${w},${e})&subset=y(${s},${n})`);
82
+ if (!res.ok)
83
+ throw new Error(`dhmv_unavailable: the height model service answered ${res.status}`);
84
+ return readGeoTiff(new Uint8Array(await res.arrayBuffer()));
85
+ },
86
+ };
87
+ }
88
+ export const DEFAULT_ROOF_PERCENTILES = { eave: 10, ridge: 99 };
89
+ /**
90
+ * The ground, eave and ridge of a footprint, from a surface model and a
91
+ * terrain model of the same grid: the median of the terrain under it, and
92
+ * two percentiles (`percentiles`, linear between cells) of the surface over
93
+ * it, each above that ground. A cell counts when its centre lies inside the
94
+ * footprint and both models have a value there. Null when no cell does: a
95
+ * footprint smaller than the grid, or outside it.
96
+ */
97
+ export function heightsInFootprint(polygons, surface, terrain, percentiles = DEFAULT_ROOF_PERCENTILES) {
98
+ if (surface.width !== terrain.width || surface.height !== terrain.height || surface.x0 !== terrain.x0 || surface.y0 !== terrain.y0) {
99
+ throw new Error('grid_mismatch: the surface and the terrain models are not on the same grid');
100
+ }
101
+ const tops = [];
102
+ const grounds = [];
103
+ const [w, s, e, n] = boxOf(polygons);
104
+ const c0 = Math.max(0, Math.floor((w - surface.x0) / surface.dx));
105
+ const c1 = Math.min(surface.width - 1, Math.ceil((e - surface.x0) / surface.dx));
106
+ const r0 = Math.max(0, Math.floor((surface.y0 - n) / surface.dy));
107
+ const r1 = Math.min(surface.height - 1, Math.ceil((surface.y0 - s) / surface.dy));
108
+ for (let r = r0; r <= r1; r += 1) {
109
+ const y = surface.y0 - (r + 0.5) * surface.dy;
110
+ for (let c = c0; c <= c1; c += 1) {
111
+ const x = surface.x0 + (c + 0.5) * surface.dx;
112
+ if (!polygons.some((p) => inPolygon(x, y, p)))
113
+ continue;
114
+ const top = surface.values[r * surface.width + c];
115
+ const ground = terrain.values[r * terrain.width + c];
116
+ if (Number.isNaN(top) || Number.isNaN(ground))
117
+ continue;
118
+ tops.push(top);
119
+ grounds.push(ground);
120
+ }
121
+ }
122
+ if (tops.length === 0)
123
+ return null;
124
+ const ground = percentile(grounds, 50);
125
+ return {
126
+ ground: round(ground),
127
+ eave: round(percentile(tops, percentiles.eave) - ground),
128
+ ridge: round(percentile(tops, percentiles.ridge) - ground),
129
+ cells: tops.length,
130
+ };
131
+ }
132
+ /** The CityObject id of a GRB building: its persistent object id, never the id of a version. */
133
+ export const grbObjectId = (oidn) => `GRB.GBG.${oidn}`;
134
+ /**
135
+ * The buildings around a point as a CityJSON model in Lambert 72, ready for
136
+ * `importCityJson()` of the `building` module: each GRB footprint at the
137
+ * height of its ground, its ridge above the ground as its measured height,
138
+ * and in its attributes its eave and ridge, the cells they were read from,
139
+ * the percentiles used and what GRB says of it. A footprint the height
140
+ * model does not cover keeps no height and is listed in `skipped`.
141
+ */
142
+ export async function siteModel(area, options = {}) {
143
+ const percentiles = options.percentiles ?? DEFAULT_ROOF_PERCENTILES;
144
+ const found = await grb({ fetch: options.fetch, baseUrl: options.grbUrl, limit: options.limit }).buildings(area);
145
+ if (found.length === 0)
146
+ return { srid: LAMBERT_72, buildings: [], skipped: [] };
147
+ const box = boxOf(found.flatMap((b) => b.polygons));
148
+ const heights = dhmv({ fetch: options.fetch, baseUrl: options.dhmvUrl });
149
+ const surface = await heights.grid('surface', box);
150
+ const terrain = await heights.grid('terrain', box);
151
+ const skipped = [];
152
+ const buildings = found.map((b) => {
153
+ const id = grbObjectId(b.oidn);
154
+ const h = heightsInFootprint(b.polygons, surface, terrain, percentiles);
155
+ if (!h)
156
+ skipped.push(`${id}: no cell of the height model inside its footprint`);
157
+ const z = h?.ground ?? 0;
158
+ return {
159
+ id,
160
+ name: null,
161
+ measuredHeight: h?.ridge ?? null,
162
+ storeysAboveGround: null,
163
+ storeysBelowGround: null,
164
+ yearOfConstruction: null,
165
+ attributes: {
166
+ grb: { oidn: b.oidn, uidn: b.uidn, type: b.type, version_date: b.versionDate, survey_date: b.surveyDate },
167
+ ...(h ? { heights: { source: 'dhmv', ground_m: h.ground, eave_m: h.eave, ridge_m: h.ridge, cells: h.cells, percentiles } } : {}),
168
+ },
169
+ footprint: b.polygons.map((rings) => rings.map((ring) => open(ring).map(([x, y]) => [x, y, z]))),
170
+ surfaces: [],
171
+ zRange: h ? [h.ground, round(h.ground + h.ridge)] : null,
172
+ };
173
+ });
174
+ return { srid: LAMBERT_72, buildings, skipped };
175
+ }
176
+ /** The `sources` rows this package ships (`sources.json`): write each with `registerSource()` of the core. */
177
+ export const grbSources = JSON.parse(readFileSync(new URL('../sources.json', import.meta.url), 'utf8'));
178
+ // ---------------------------------------------------------------------------
179
+ /** A box in degrees around a point: west, south, east, north. */
180
+ function degreesAround(area) {
181
+ if (!(area.radiusM > 0))
182
+ throw new Error('radius_required: a radius in metres, above zero');
183
+ const dLat = area.radiusM / 111_320;
184
+ const dLon = area.radiusM / (111_320 * Math.cos((area.lat * Math.PI) / 180));
185
+ return [area.lon - dLon, area.lat - dLat, area.lon + dLon, area.lat + dLat];
186
+ }
187
+ function boxOf(polygons) {
188
+ let [w, s, e, n] = [Infinity, Infinity, -Infinity, -Infinity];
189
+ for (const rings of polygons) {
190
+ for (const [x, y] of rings[0] ?? []) {
191
+ w = Math.min(w, x);
192
+ s = Math.min(s, y);
193
+ e = Math.max(e, x);
194
+ n = Math.max(n, y);
195
+ }
196
+ }
197
+ return [w, s, e, n];
198
+ }
199
+ /** Inside the outer ring and outside every hole, by the even-odd rule. */
200
+ function inPolygon(x, y, rings) {
201
+ let inside = false;
202
+ for (const ring of rings) {
203
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {
204
+ const [xi, yi] = ring[i];
205
+ const [xj, yj] = ring[j];
206
+ if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi)
207
+ inside = !inside;
208
+ }
209
+ }
210
+ return inside;
211
+ }
212
+ /** The p-th percentile, linear between the two closest ranks. */
213
+ function percentile(values, p) {
214
+ const sorted = [...values].sort((a, b) => a - b);
215
+ const rank = (Math.min(Math.max(p, 0), 100) / 100) * (sorted.length - 1);
216
+ const lo = Math.floor(rank);
217
+ const hi = Math.ceil(rank);
218
+ return sorted[lo] + (sorted[hi] - sorted[lo]) * (rank - lo);
219
+ }
220
+ /** A closed ring as CityJSON writes it: the last point not repeated. */
221
+ function open(ring) {
222
+ const [a, b] = [ring[0], ring[ring.length - 1]];
223
+ return ring.length > 1 && a[0] === b[0] && a[1] === b[1] ? ring.slice(0, -1) : ring;
224
+ }
225
+ const round = (v) => Math.round(v * 100) / 100;
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@nexgen-os/grb",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.5.0",
4
+ "description": "The buildings of a place in Flanders from open data — GRB footprints and their ground, eave and ridge from DHM Vlaanderen II — as a CityJSON model for the building module of Nexgen OS.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/nexgen-os/nexgen-os.git",
9
+ "directory": "packages/connectors/grb"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE",
22
+ "sources.json"
23
+ ],
24
+ "main": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js"
30
+ }
31
+ },
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.build.json"
34
+ },
35
+ "dependencies": {
36
+ "@nexgen-os/cityjson": "^0.5.0",
37
+ "@nexgen-os/core": "^0.5.0"
38
+ }
39
+ }
package/sources.json ADDED
@@ -0,0 +1,34 @@
1
+ [
2
+ {
3
+ "code": "grb",
4
+ "name": "GRB — Large-scale Reference Database of Flanders",
5
+ "description": "Every building on the ground in Flanders drawn by Digitaal Vlaanderen at large scale (layer GBG), with a persistent object id and the date of its version, through a Web Feature Service in Belgian Lambert 72. Read by @nexgen-os/grb.",
6
+ "kind": "api",
7
+ "base_url": "https://geo.api.vlaanderen.be/GRB/wfs",
8
+ "docs_url": "https://www.vlaanderen.be/digitaal-vlaanderen/onze-diensten-en-platformen/basiskaart-vlaanderen-grb",
9
+ "auth": "none",
10
+ "countries": ["BE"],
11
+ "regions": ["BE-VLG"],
12
+ "license": "Modellicentie Gratis Hergebruik",
13
+ "attribution": "© Digitaal Vlaanderen — GRB",
14
+ "retention_days": null,
15
+ "redistributable": true,
16
+ "published_by": "@nexgen-os/grb"
17
+ },
18
+ {
19
+ "code": "dhmv",
20
+ "name": "DHM Vlaanderen II — Digital Height Model of Flanders",
21
+ "description": "The surface the airborne laser saw (DSM, roofs and trees) and the terrain under it (DTM) over Flanders, at 1 m, in metres above the Ostend datum, through a Web Coverage Service in Belgian Lambert 72. Read by @nexgen-os/grb for the heights of buildings.",
22
+ "kind": "api",
23
+ "base_url": "https://geo.api.vlaanderen.be/DHMV/wcs",
24
+ "docs_url": "https://www.vlaanderen.be/digitaal-vlaanderen/onze-oplossingen/earth-observation-data-science-eodas/het-digitaal-hoogtemodel",
25
+ "auth": "none",
26
+ "countries": ["BE"],
27
+ "regions": ["BE-VLG"],
28
+ "license": "Modellicentie Gratis Hergebruik",
29
+ "attribution": "© Digitaal Vlaanderen — DHM Vlaanderen II",
30
+ "retention_days": null,
31
+ "redistributable": true,
32
+ "published_by": "@nexgen-os/grb"
33
+ }
34
+ ]