coastlines 0.0.7-alpha.0 → 0.0.8-alpha.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/README.md CHANGED
@@ -111,6 +111,18 @@ the GSHHG zip. `coastlines/manifest.json` is the machine-readable form of this
111
111
  table, with the bytes and sha256 of each file and, under `sources`, of the
112
112
  zip itself.
113
113
 
114
+ ### Installed, built, or cached
115
+
116
+ | Where | What | Size | How it reaches you |
117
+ | --- | --- | ---: | --- |
118
+ | `data/` | the 36 files above | 78 MB, 29 MB packed | installed with the package |
119
+ | `geo/` | six cut bands, land and water in square cells | 896 MB | built by `npm run sync`; not shipped |
120
+ | `cache/` | the GSHHG zip, six Natural Earth 10m water files | 167 MB | fetched once by sync, kept |
121
+
122
+ The cut bands are Natural Earth 10m and GSHHG h and f, land and lakes, each
123
+ a record in `catalogue.json`: grid, inputs and pins, cutter and build date.
124
+ How cells reach a boat that installs the package is open ([#17](https://github.com/mark-brannan/coastlines/issues/17)).
125
+
114
126
  ### Sources and licences
115
127
 
116
128
  Natural Earth is public domain. GSHHG (Wessel & Smith, the Global
@@ -146,7 +158,7 @@ release and refuses any byte that disagrees with `manifest.json`; `npm pack`
146
158
  runs it first, so a tarball never ships a file the manifest did not promise.
147
159
 
148
160
  ```shell
149
- npm run sync # fetch what is missing, verify everything (45 MB + 149 MB zip)
161
+ npm run sync # fetch what is missing, verify everything, cut the cells (~2 min, 6 GB heap)
150
162
  npm run sync:check # verify only, no network
151
163
  npm run sync:refresh # move the pins: refetch all and rewrite bytes and sha256
152
164
  ```
package/catalogue.json CHANGED
@@ -1046,7 +1046,9 @@
1046
1046
  "licence": "public domain",
1047
1047
  "version": "v5.1.2",
1048
1048
  "date": "2022-05-13",
1049
- "caveat": "Holds to about z12 but has no narrow channels"
1049
+ "caveat": "Holds to about z12 but has no narrow channels",
1050
+ "cutter": "coastlines/lib/cut.js",
1051
+ "built": "2026-10-15"
1050
1052
  },
1051
1053
  "bytesPerCell": null,
1052
1054
  "bytes": null,
@@ -1086,7 +1088,9 @@
1086
1088
  "licence": "LGPL-3.0-or-later",
1087
1089
  "version": "2.3.7",
1088
1090
  "date": "2017-06-15",
1089
- "caveat": "Holds to about z13; draws the Seattle ship canal. Its licence files are owned here and travel with every GSHHG band"
1091
+ "caveat": "Holds to about z13; draws the Seattle ship canal. Its licence files are owned here and travel with every GSHHG band",
1092
+ "cutter": "coastlines/lib/cut.js",
1093
+ "built": "2026-10-15"
1090
1094
  },
1091
1095
  "bytesPerCell": null,
1092
1096
  "bytes": null,
@@ -1118,7 +1122,9 @@
1118
1122
  "licence": "LGPL-3.0-or-later",
1119
1123
  "version": "2.3.7",
1120
1124
  "date": "2017-06-15",
1121
- "caveat": "Full resolution; about 70,000 cells"
1125
+ "caveat": "Full resolution; about 70,000 cells",
1126
+ "cutter": "coastlines/lib/cut.js",
1127
+ "built": "2026-10-15"
1122
1128
  },
1123
1129
  "bytesPerCell": null,
1124
1130
  "bytes": null,
@@ -1169,7 +1175,9 @@
1169
1175
  "licence": "public domain",
1170
1176
  "version": "v5.1.2",
1171
1177
  "date": "2022-05-13",
1172
- "caveat": "Rivers and lakes with their regional supplements; whole features go into every cell they reach. Not in the manifest, so each file is pinned here"
1178
+ "caveat": "Rivers and lakes with their regional supplements; whole features go into every cell they reach. Not in the manifest, so each file is pinned here",
1179
+ "cutter": "coastlines/lib/cut.js",
1180
+ "built": "2026-10-15"
1173
1181
  },
1174
1182
  "bytesPerCell": null,
1175
1183
  "bytes": null,
@@ -1247,7 +1255,9 @@
1247
1255
  "licence": "LGPL-3.0-or-later",
1248
1256
  "version": "2.3.7",
1249
1257
  "date": "2017-06-15",
1250
- "caveat": "Lakes no Natural Earth file has (Dian Chi, Lago Mascardi); levels 2 and 3 with river-lakes"
1258
+ "caveat": "Lakes no Natural Earth file has (Dian Chi, Lago Mascardi); levels 2 and 3 with river-lakes",
1259
+ "cutter": "coastlines/lib/cut.js",
1260
+ "built": "2026-10-15"
1251
1261
  },
1252
1262
  "bytesPerCell": null,
1253
1263
  "bytes": null,
@@ -1311,7 +1321,9 @@
1311
1321
  "licence": "LGPL-3.0-or-later",
1312
1322
  "version": "2.3.7",
1313
1323
  "date": "2017-06-15",
1314
- "caveat": "As gshhg-h-lakes at full resolution"
1324
+ "caveat": "As gshhg-h-lakes at full resolution",
1325
+ "cutter": "coastlines/lib/cut.js",
1326
+ "built": "2026-10-15"
1315
1327
  },
1316
1328
  "bytesPerCell": null,
1317
1329
  "bytes": null,
package/lib/bands.js CHANGED
@@ -16,6 +16,9 @@ import { charts } from './charts.js';
16
16
 
17
17
  const require = createRequire(import.meta.url);
18
18
 
19
+ /** What a cut band's `provenance.cutter` names: the module that builds its cells. */
20
+ export const CUTTER = 'coastlines/lib/cut.js';
21
+
19
22
  /** The parsed catalogue.json: one record per band, whole Natural Earth files first. */
20
23
  export const catalogue = require('../catalogue.json');
21
24
 
@@ -72,6 +75,20 @@ function wholeFileDrift(record) {
72
75
  return problems;
73
76
  }
74
77
 
78
+ /** A cut band names its cutter and the day it was built, and draws on one upstream only. */
79
+ function cutDrift(record) {
80
+ const problems = [];
81
+ const { cutter, built } = record.provenance;
82
+ if (cutter !== CUTTER) problems.push(`${record.id}: cutter ${cutter} is not ${CUTTER}`);
83
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(built ?? ''))
84
+ problems.push(`${record.id}: built ${built} is not a date`);
85
+ const sources = new Set(
86
+ inputsOf(record).map((i) => (typeof i === 'string' ? find(i).source : i.source)),
87
+ );
88
+ if (sources.size !== 1) problems.push(`${record.id}: mixes sources ${[...sources].join(', ')}`);
89
+ return problems;
90
+ }
91
+
75
92
  /**
76
93
  * Where the catalogue and the manifest disagree, as sentences; empty when they agree. Every
77
94
  * record's upstream URLs, members and sha256s must be what its inputs pin, its licence, version
@@ -105,6 +122,7 @@ export function drift() {
105
122
  if (date !== from.date) problems.push(`${record.id}: date ${date} is not ${key}'s`);
106
123
  }
107
124
  if (record.grid === null) problems.push(...wholeFileDrift(record));
125
+ else problems.push(...cutDrift(record));
108
126
  } catch (error) {
109
127
  problems.push(`${record.id}: ${error.message}`);
110
128
  }
package/lib/cut.js ADDED
@@ -0,0 +1,138 @@
1
+ // Builds the catalogue's `cells` sources: each cut band's inputs, read through `read`, cut into
2
+ // square lon/lat cells under geo/<dir>/ (<xi>_<yi>.json and index.json). A band is cut from one
3
+ // upstream only, so no geometry file mixes sources.
4
+ import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
5
+ import { band, CUTTER, inputsOf } from './bands.js';
6
+ import { find } from './catalogue.js';
7
+ import { shapefilePolygons } from './shapefile.js';
8
+ import { cutCells, cutLakes, cutWater, dbfRecords, gshhgLakes, joinWater } from './detail-cells.js';
9
+
10
+ /** The folder under geo/ of a band's `cells` source: `geo/f/` is `f`. */
11
+ export const cellsDir = (record) =>
12
+ record.sources.find((source) => source.kind === 'cells').url.replace(/^geo\/|\/$/g, '');
13
+
14
+ const json = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
15
+
16
+ function polygons(geojson) {
17
+ const out = [];
18
+ for (const { geometry } of geojson.features) {
19
+ if (geometry?.type === 'Polygon') out.push(geometry.coordinates);
20
+ else if (geometry?.type === 'MultiPolygon') for (const p of geometry.coordinates) out.push(p);
21
+ }
22
+ return out;
23
+ }
24
+
25
+ function lines(geojson) {
26
+ const out = [];
27
+ for (const { geometry } of geojson.features) {
28
+ if (geometry?.type === 'LineString') out.push(geometry.coordinates);
29
+ else if (geometry?.type === 'MultiLineString')
30
+ for (const l of geometry.coordinates) out.push(l);
31
+ }
32
+ return out;
33
+ }
34
+
35
+ /**
36
+ * The cells of a band: Map(key -> cell). `read(input)` returns the bytes of one input, as
37
+ * `inputsOf(record)` lists them.
38
+ */
39
+ export async function cutBand(record, read) {
40
+ const size = record.grid.cellDeg;
41
+ const bytes = await Promise.all(inputsOf(record).map(read));
42
+ if (record.id === 'ne-10m-land') {
43
+ const [land, coast, minor] = bytes.map(json);
44
+ return cutCells(
45
+ { land: polygons(land), coast: [...lines(coast), ...polygons(minor).map((p) => p[0])] },
46
+ size,
47
+ );
48
+ }
49
+ if (record.layer === 'land') {
50
+ const land = shapefilePolygons(bytes[0]);
51
+ return cutCells({ land, coast: land.flat() }, size);
52
+ }
53
+ if (record.layer === 'water') {
54
+ const [rivers, lakes] = [bytes.slice(0, 3), bytes.slice(3)].map((half) =>
55
+ joinWater(half.map(json)),
56
+ );
57
+ return cutWater(rivers, lakes, { size });
58
+ }
59
+ if (record.layer === 'lakes') {
60
+ const [l2, d2, l3, d3] = bytes;
61
+ return cutLakes(
62
+ gshhgLakes(shapefilePolygons(l2), dbfRecords(d2), shapefilePolygons(l3), dbfRecords(d3)),
63
+ size,
64
+ );
65
+ }
66
+ throw new Error(`${record.id}: no cutter for layer ${record.layer}`);
67
+ }
68
+
69
+ /** Writes a band's cells to `root`/geo/<dir>/, complete or not at all; returns the cell count. */
70
+ export async function writeBand(record, cells, root) {
71
+ const final = new URL(`geo/${cellsDir(record)}/`, root);
72
+ const partial = new URL(`geo/${cellsDir(record)}.partial/`, root);
73
+ await rm(partial, { recursive: true, force: true });
74
+ await mkdir(partial, { recursive: true });
75
+ // in batches: "f" has some 70,000 cells, past an open-file limit if written at once
76
+ const all = [...cells];
77
+ for (let i = 0; i < all.length; i += 512)
78
+ await Promise.all(
79
+ all
80
+ .slice(i, i + 512)
81
+ .map(([k, c]) => writeFile(new URL(`${k}.json`, partial), JSON.stringify(c))),
82
+ );
83
+ await writeFile(
84
+ new URL('index.json', partial),
85
+ JSON.stringify({ cell: record.grid.cellDeg, cells: [...cells.keys()] }),
86
+ );
87
+ await rm(final, { recursive: true, force: true });
88
+ await rename(partial, final);
89
+ return cells.size;
90
+ }
91
+
92
+ /**
93
+ * catalogue.json's text with one record's `provenance.built` set to `day`, every other byte as it
94
+ * was. Throws rather than touch the wrong record: the id must be there, and the `built` must sit
95
+ * in that record, before the next `"id":`.
96
+ */
97
+ export function stampBuilt(text, id, day) {
98
+ const at = text.indexOf(`"id": "${id}"`);
99
+ if (at < 0) throw new Error(`${id}: not in catalogue.json`);
100
+ const end = text.indexOf('"id": "', at + 1);
101
+ const record = text.slice(at, end < 0 ? undefined : end);
102
+ const stamped = record.replace(/("built": )"[^"]*"/, `$1"${day}"`);
103
+ if (stamped === record && !record.includes(`"built": "${day}"`))
104
+ throw new Error(`${id}: no provenance.built to stamp`);
105
+ return text.slice(0, at) + stamped + (end < 0 ? '' : text.slice(end));
106
+ }
107
+
108
+ /** The cut bands whose inputs are GSHHG's, which the notice below covers. */
109
+ export const modifiedGshhg = (catalogue) =>
110
+ catalogue.filter(
111
+ (r) =>
112
+ r.grid &&
113
+ inputsOf(r).some((i) => (typeof i === 'string' ? find(i).source : i.source) === 'gshhg'),
114
+ );
115
+
116
+ /** The text of geo/gshhg-modified.txt for the bands built, with the dates they were cut. */
117
+ export function modifiedNotice(records) {
118
+ const rows = records
119
+ .map((r) => ` geo/${cellsDir(r)}/ ${r.id}, cut ${r.provenance.built}`)
120
+ .join('\n');
121
+ return `GSHHG, modified
122
+ ===============
123
+
124
+ The cell files below are modified GSHHG ${band(records[0].id).provenance.version} (Wessel & Smith), not the
125
+ published shapefiles. They were made by ${CUTTER} from the pinned zip: polygons
126
+ clipped to square lon/lat cells, shorelines split where they pass from one cell to the next,
127
+ coordinates rounded to 5 decimals, and each land polygon annotated with the area and colour of the
128
+ island it is a piece of.
129
+
130
+ ${rows}
131
+
132
+ Licence: GNU Lesser General Public License version 3 or later, conveyed under section 5(a) of the
133
+ GNU General Public License version 3, which asks for a notice that the work was modified and the
134
+ date of the modification: this file. The unmodified originals are fetched, byte for byte, by
135
+ \`npm run sync\`; their copyright and permission notice and the licence text are in
136
+ data/gshhg-licence.txt and data/gshhg-copying-lesser.txt and apply to the cells too.
137
+ `;
138
+ }
@@ -0,0 +1,313 @@
1
+ // Cuts Natural Earth 10m land and coast into square lon/lat cells, so a close view fetches only the
2
+ // few cells around it rather than the whole 10m world. Land polygons are clipped to each cell (fill
3
+ // is even-odd, so the cut edges vanish; each cell's `m` holds, for its land polygons in order, the
4
+ // area in km2 and colour of the island each is a piece of, worked out before the cut); coast lines are split where they pass from one cell to the
5
+ // next, each piece keeping the shared point so the line stays joined. Coordinates are rounded to
6
+ // `digits` decimals (5 is about a metre). Cell keys are `${xi}_${yi}`, xi = floor(lon / size).
7
+
8
+ import { islandInfo } from './island.js';
9
+
10
+ const key = (xi, yi) => `${xi}_${yi}`;
11
+
12
+ // Sutherland-Hodgman against one axis-aligned half-plane: keep points with p[axis] <= v (keep < 0)
13
+ // or >= v (keep > 0). `ring` is open (last point not repeated).
14
+ function clipHalf(ring, axis, v, keep) {
15
+ const out = [],
16
+ inside = (p) => (keep < 0 ? p[axis] <= v : p[axis] >= v);
17
+ for (let i = 0; i < ring.length; i++) {
18
+ const a = ring[i],
19
+ b = ring[(i + 1) % ring.length],
20
+ ia = inside(a),
21
+ ib = inside(b);
22
+ if (ia) out.push(a);
23
+ if (ia !== ib) {
24
+ const t = (v - a[axis]) / (b[axis] - a[axis]);
25
+ const p = [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])];
26
+ p[axis] = v;
27
+ out.push(p);
28
+ }
29
+ }
30
+ return out;
31
+ }
32
+
33
+ function ringBox(ring) {
34
+ let x0 = Infinity,
35
+ y0 = Infinity,
36
+ x1 = -Infinity,
37
+ y1 = -Infinity;
38
+ for (const [x, y] of ring) {
39
+ if (x < x0) x0 = x;
40
+ if (x > x1) x1 = x;
41
+ if (y < y0) y0 = y;
42
+ if (y > y1) y1 = y;
43
+ }
44
+ return [x0, y0, x1, y1];
45
+ }
46
+
47
+ // Polygons ([[outer, ...holes]], open rings) into cells by recursive halving along cell lines, so
48
+ // each point is clipped about log2(cells) times rather than once per cell.
49
+ function splitPolygons(polys, box, size, emit) {
50
+ if (!polys.length) return;
51
+ const [x0, y0, x1, y1] = box,
52
+ nx = Math.round((x1 - x0) / size),
53
+ ny = Math.round((y1 - y0) / size);
54
+ if (nx <= 1 && ny <= 1) {
55
+ emit(Math.round(x0 / size), Math.round(y0 / size), polys);
56
+ return;
57
+ }
58
+ const axis = nx >= ny ? 0 : 1,
59
+ mid = axis === 0 ? x0 + Math.floor(nx / 2) * size : y0 + Math.floor(ny / 2) * size;
60
+ const lo = [],
61
+ hi = [];
62
+ for (const poly of polys) {
63
+ const b = ringBox(poly[0]);
64
+ if (b[axis + 2] <= mid) {
65
+ lo.push(poly);
66
+ continue;
67
+ }
68
+ if (b[axis] >= mid) {
69
+ hi.push(poly);
70
+ continue;
71
+ }
72
+ for (const [side, keep] of [
73
+ [lo, -1],
74
+ [hi, 1],
75
+ ]) {
76
+ const [outer, ...holes] = poly.map((r) => clipHalf(r, axis, mid, keep));
77
+ if (outer.length >= 3)
78
+ side.push(Object.assign([outer, ...holes.filter((r) => r.length >= 3)], { isl: poly.isl }));
79
+ }
80
+ }
81
+ const loBox = axis === 0 ? [x0, y0, mid, y1] : [x0, y0, x1, mid],
82
+ hiBox = axis === 0 ? [mid, y0, x1, y1] : [x0, mid, x1, y1];
83
+ splitPolygons(lo, loBox, size, emit);
84
+ splitPolygons(hi, hiBox, size, emit);
85
+ }
86
+
87
+ // `land`: GeoJSON polygons as [[outer, ...holes]] of closed [lon, lat] rings; `coast`: lines of
88
+ // [lon, lat]. Returns Map(key -> { land, coast, m }), rings closed again, coordinates rounded; `m`
89
+ // holds `meta` of the whole polygon each land piece was cut from (by default its island's area and colour).
90
+ const islandMeta = (poly) => {
91
+ const i = islandInfo(poly);
92
+ return [i.km2, i.hue];
93
+ };
94
+ export function cutCells({ land, coast }, size = 5, digits = 5, meta = islandMeta) {
95
+ const f = 10 ** digits,
96
+ round = (p) => [Math.round(p[0] * f) / f, Math.round(p[1] * f) / f];
97
+ const tidy = (pts) =>
98
+ pts.map(round).filter((p, i, a) => i === 0 || p[0] !== a[i - 1][0] || p[1] !== a[i - 1][1]);
99
+ const cells = new Map(),
100
+ cell = (k) => cells.get(k) ?? cells.set(k, { land: [], coast: [], m: [] }).get(k);
101
+ const ids = coast.some((l) => l.id !== undefined); // and if lines carry an `id`, `cm` holds each piece's
102
+
103
+ const open = (r) =>
104
+ r.length > 1 && r[0][0] === r[r.length - 1][0] && r[0][1] === r[r.length - 1][1]
105
+ ? r.slice(0, -1)
106
+ : r;
107
+ splitPolygons(
108
+ land.map((poly) => Object.assign(poly.map(open), { isl: meta(poly) })),
109
+ [-180, -90, 180, 90],
110
+ size,
111
+ (xi, yi, polys) => {
112
+ const c = cell(key(xi, yi)),
113
+ out = c.land;
114
+ for (const poly of polys) {
115
+ const rings = poly
116
+ .map(tidy)
117
+ .filter((r) => r.length >= 3)
118
+ .map((r) => [...r, r[0]]);
119
+ if (rings.length) {
120
+ out.push(rings);
121
+ c.m.push(poly.isl);
122
+ }
123
+ }
124
+ },
125
+ );
126
+
127
+ // A segment belongs to the cell holding its midpoint; a run of segments in one cell is one piece.
128
+ const cellOf = (a, b) =>
129
+ key(Math.floor((a[0] + b[0]) / 2 / size), Math.floor((a[1] + b[1]) / 2 / size));
130
+ const put = (k, piece, id) => {
131
+ const c = cell(k);
132
+ c.coast.push(piece);
133
+ if (ids) (c.cm ??= []).push(id);
134
+ };
135
+ for (const line of coast) {
136
+ let piece = null,
137
+ at = null;
138
+ for (let i = 0; i < line.length - 1; i++) {
139
+ const k = cellOf(line[i], line[i + 1]);
140
+ if (k !== at) {
141
+ if (piece) put(at, piece, line.id);
142
+ piece = [line[i]];
143
+ at = k;
144
+ }
145
+ piece.push(line[i + 1]);
146
+ }
147
+ if (piece) put(at, piece, line.id);
148
+ }
149
+ for (const c of cells.values()) {
150
+ const lines = c.coast.map(tidy),
151
+ keep = lines.map((l) => l.length > 1);
152
+ c.coast = lines.filter((_, i) => keep[i]);
153
+ if (c.cm) c.cm = c.cm.filter((_, i) => keep[i]);
154
+ }
155
+ return cells;
156
+ }
157
+
158
+ // The Natural Earth 10m water downloads, the world file first and then the regional supplements,
159
+ // which hold what the world file leaves out (Lake Washington, Como, the Snohomish) and repeat none of
160
+ // it. joinWater makes one collection of several, in this order, so cutWater's ids stay unique.
161
+ export const WATER_FILES = {
162
+ rivers: [
163
+ 'ne_10m_rivers_lake_centerlines.geojson',
164
+ 'ne_10m_rivers_north_america.geojson',
165
+ 'ne_10m_rivers_europe.geojson',
166
+ ],
167
+ lakes: [
168
+ 'ne_10m_lakes.geojson',
169
+ 'ne_10m_lakes_north_america.geojson',
170
+ 'ne_10m_lakes_europe.geojson',
171
+ ],
172
+ };
173
+ export const joinWater = (geos) => ({
174
+ type: 'FeatureCollection',
175
+ features: geos.flatMap((g) => g?.features ?? []),
176
+ });
177
+
178
+ // Natural Earth rivers and lakes into the same square cells, for scripts/water.mjs past WATER_ZOOM.
179
+ // A feature goes whole into every cell it reaches (a river, each cell its segments' midpoints and
180
+ // vertices fall in; a lake, each cell its box meets), so a river keeps one wiggle and a lake one
181
+ // outline wherever the view is cut; its index in the source file is its GeoJSON `id`, by which
182
+ // the scene keeps one copy of a feature fetched from several cells. Properties are cut to `keep`.
183
+ // Returns Map(key -> { rivers, lakes }), each a FeatureCollection.
184
+ export function cutWater(
185
+ riversGeo,
186
+ lakesGeo,
187
+ {
188
+ keep = { rivers: ['name', 'featurecla', 'min_zoom'], lakes: ['name', 'min_zoom'] },
189
+ size = 5,
190
+ digits = 5,
191
+ } = {},
192
+ ) {
193
+ const f = 10 ** digits,
194
+ round = (c) =>
195
+ typeof c[0] === 'number'
196
+ ? [Math.round(c[0] * f) / f, Math.round(c[1] * f) / f]
197
+ : c.map(round);
198
+ const cells = new Map(),
199
+ cell = (k) => cells.get(k) ?? cells.set(k, { rivers: [], lakes: [] }).get(k);
200
+ // 180 east and 90 north fall in the last cell, not one past it
201
+ const xiOf = (lon) => Math.min(180 / size - 1, Math.floor(lon / size)),
202
+ yiOf = (lat) => Math.min(90 / size - 1, Math.floor(lat / size));
203
+ const at = (lon, lat) => key(xiOf(lon), yiOf(lat));
204
+ const lines = (g) =>
205
+ g.type === 'LineString'
206
+ ? [g.coordinates]
207
+ : g.type === 'MultiLineString'
208
+ ? g.coordinates
209
+ : g.type === 'Polygon'
210
+ ? g.coordinates
211
+ : g.type === 'MultiPolygon'
212
+ ? g.coordinates.flat()
213
+ : [];
214
+ const reach = {
215
+ rivers: (g) => {
216
+ const ks = new Set();
217
+ for (const l of lines(g))
218
+ l.forEach((p, i) => {
219
+ ks.add(at(p[0], p[1]));
220
+ if (i) ks.add(at((p[0] + l[i - 1][0]) / 2, (p[1] + l[i - 1][1]) / 2));
221
+ });
222
+ return ks;
223
+ },
224
+ lakes: (g) => {
225
+ const [x0, y0, x1, y1] = ringBox(lines(g).flat()),
226
+ ks = new Set();
227
+ for (let xi = xiOf(x0); xi <= xiOf(x1); xi++)
228
+ for (let yi = yiOf(y0); yi <= yiOf(y1); yi++) ks.add(key(xi, yi));
229
+ return ks;
230
+ },
231
+ };
232
+ for (const [kind, geo] of [
233
+ ['rivers', riversGeo],
234
+ ['lakes', lakesGeo],
235
+ ]) {
236
+ (geo?.features ?? []).forEach((ft, id) => {
237
+ if (!ft.geometry) return;
238
+ const slim = {
239
+ type: 'Feature',
240
+ id,
241
+ properties: Object.fromEntries(keep[kind].map((k) => [k, ft.properties[k]])),
242
+ geometry: { type: ft.geometry.type, coordinates: round(ft.geometry.coordinates) },
243
+ };
244
+ for (const k of reach[kind](ft.geometry)) cell(k)[kind].push(slim);
245
+ });
246
+ }
247
+ for (const [k, c] of cells)
248
+ cells.set(k, {
249
+ rivers: { type: 'FeatureCollection', features: c.rivers },
250
+ lakes: { type: 'FeatureCollection', features: c.lakes },
251
+ });
252
+ return cells;
253
+ }
254
+
255
+ // GSHHG lakes (level 2, river-lakes among them) with their islands (level 3) as holes, from the
256
+ // shapefiles' polygons and dBASE records, for cutLakes. Each lake carries its GSHHG id and its
257
+ // whole lon/lat box, which its cut pieces keep: the scene drops a 10m lake inside one.
258
+ export function dbfRecords(bytes) {
259
+ const b = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
260
+ const n = b.readUInt32LE(4),
261
+ headLength = b.readUInt16LE(8),
262
+ recordLength = b.readUInt16LE(10),
263
+ fields = [];
264
+ for (let at = 32, o = 1; b[at] !== 0x0d; at += 32) {
265
+ const name = b.toString('latin1', at, at + 11).replace(/\0.*/s, ''),
266
+ length = b[at + 16];
267
+ fields.push([name, o, length]);
268
+ o += length;
269
+ }
270
+ return Array.from({ length: n }, (_, i) =>
271
+ Object.fromEntries(
272
+ fields.map(([k, o, l]) => [
273
+ k,
274
+ b
275
+ .toString(
276
+ 'latin1',
277
+ headLength + i * recordLength + o,
278
+ headLength + i * recordLength + o + l,
279
+ )
280
+ .trim(),
281
+ ]),
282
+ ),
283
+ );
284
+ }
285
+ export function gshhgLakes(lakes, lakeRecords, islands, islandRecords) {
286
+ const byId = new Map(
287
+ lakes.map((poly, i) => [
288
+ lakeRecords[i].id,
289
+ Object.assign([...poly], { id: +lakeRecords[i].id }),
290
+ ]),
291
+ );
292
+ islands.forEach((poly, i) => byId.get(islandRecords[i].parent_id)?.push(poly[0]));
293
+ return [...byId.values()];
294
+ }
295
+ // Lakes into cells as land is (cutCells): pieces clipped to each cell to fill, and the shores split
296
+ // at cell edges to ink, so a cut edge is never drawn. `m` holds, per piece, [id, x0, y0, x1, y1]: the
297
+ // lake's id and whole box, rounded out to `digits`; `cm` each shore piece's lake id.
298
+ export function cutLakes(lakes, size, digits = 5) {
299
+ const f = 10 ** digits;
300
+ const shores = lakes.flatMap((lake) =>
301
+ lake.map((ring) => Object.assign([...ring], { id: lake.id })),
302
+ );
303
+ return cutCells({ land: lakes, coast: shores }, size, digits, (poly) => {
304
+ const [x0, y0, x1, y1] = ringBox(poly[0]);
305
+ return [
306
+ poly.id,
307
+ Math.floor(x0 * f) / f,
308
+ Math.floor(y0 * f) / f,
309
+ Math.ceil(x1 * f) / f,
310
+ Math.ceil(y1 * f) / f,
311
+ ];
312
+ });
313
+ }
package/lib/island.js ADDED
@@ -0,0 +1,51 @@
1
+ // What the land treatments need to know about an island: its area in km2 and a colour that stays
2
+ // with it. Computed once per land polygon, from the whole polygon (so before lib/detail-cells.js
3
+ // cuts it into cells, which carry the result along), and shared by the scene and the cutter.
4
+
5
+ export const ISLAND_KM2 = 5000; // coloured islands are the land polygons smaller than this
6
+ export const ISLAND_HUES = 3; // red, green, gold
7
+
8
+ const R_KM = 6371.0088,
9
+ RAD = Math.PI / 180;
10
+
11
+ // Area of a [lon, lat] ring (open or closed) in km2: equirectangular about the ring's own latitude,
12
+ // good to a percent or two at this size.
13
+ function ringKm2(ring) {
14
+ const lat0 = ring.reduce((s, p) => s + p[1], 0) / ring.length,
15
+ lon0 = ring[0][0],
16
+ c = Math.cos(lat0 * RAD);
17
+ const pt = ([lon, lat]) => [(((lon - lon0 + 540) % 360) - 180) * c, lat];
18
+ let s = 0;
19
+ for (let i = 0; i < ring.length; i++) {
20
+ const [x1, y1] = pt(ring[i]),
21
+ [x2, y2] = pt(ring[(i + 1) % ring.length]);
22
+ s += x1 * y2 - x2 * y1;
23
+ }
24
+ return (Math.abs(s) / 2) * (R_KM * RAD) ** 2;
25
+ }
26
+
27
+ // { km2, hue } of a polygon [outer, ...holes]. The hue comes from the centre of the outer ring's
28
+ // box, to a tenth of a degree: the same island has the same colour in every view and, to within a
29
+ // tenth of a degree of disagreement between data sets, at every zoom.
30
+ export function islandInfo(poly) {
31
+ const km2 = Math.round(ringKm2(poly[0]) - poly.slice(1).reduce((s, r) => s + ringKm2(r), 0));
32
+ let x0 = Infinity,
33
+ x1 = -Infinity,
34
+ y0 = Infinity,
35
+ y1 = -Infinity;
36
+ const lon0 = poly[0][0][0];
37
+ for (const [lon, lat] of poly[0]) {
38
+ const x = ((lon - lon0 + 540) % 360) - 180;
39
+ if (x < x0) x0 = x;
40
+ if (x > x1) x1 = x;
41
+ if (lat < y0) y0 = lat;
42
+ if (lat > y1) y1 = lat;
43
+ }
44
+ let h =
45
+ Math.imul(Math.round((lon0 + (x0 + x1) / 2) * 10), 0x9e3779b1) ^
46
+ Math.imul(Math.round((y0 + y1) * 5), 0x85ebca6b);
47
+ h ^= h >>> 15;
48
+ h = Math.imul(h, 0x2c1b3c6d);
49
+ h ^= h >>> 13;
50
+ return { km2, hue: (h >>> 0) % ISLAND_HUES };
51
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "coastlines",
3
- "version": "0.0.7-alpha.0",
3
+ "version": "0.0.8-alpha.0",
4
4
  "description": "Natural Earth geography on a boat, installed rather than fetched: the marine catalogue at three scales, byte-for-byte as published, sha256-pinned, as plain GeoJSON today and a Signal K resource provider next",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -19,10 +19,10 @@
19
19
  },
20
20
  "scripts": {
21
21
  "test": "node --test",
22
- "sync": "node scripts/sync.mjs",
23
- "sync:check": "node scripts/sync.mjs --check",
24
- "sync:refresh": "node scripts/sync.mjs --refresh",
25
- "prepack": "node scripts/sync.mjs",
22
+ "sync": "node --max-old-space-size=6144 scripts/sync.mjs",
23
+ "sync:check": "node --max-old-space-size=6144 scripts/sync.mjs --check",
24
+ "sync:refresh": "node --max-old-space-size=6144 scripts/sync.mjs --refresh",
25
+ "prepack": "node scripts/sync.mjs --no-cells",
26
26
  "build:sheet": "node scripts/render-sheet.mjs",
27
27
  "build:readme": "node scripts/catalogue-table.mjs",
28
28
  "build:pages": "node scripts/build-pages.mjs",