@orbat-mapper/tactical-map-sheet 0.7.0 → 0.8.1

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.
@@ -661,7 +661,10 @@ function serializeText(text) {
661
661
  return `${background}<text ${attributes.join(" ")}>${content}</text>`;
662
662
  }
663
663
  function serializeElement(element) {
664
- if (element.kind === "raster-image") return `<image data-raster-resource="${escapeXml(element.resourceId)}" x="${formatDecimal(element.frame.xMm)}" y="${formatDecimal(element.frame.yMm)}" width="${formatDecimal(element.frame.widthMm)}" height="${formatDecimal(element.frame.heightMm)}" opacity="${formatDecimal(element.opacity)}" preserveAspectRatio="none" href="data:${element.mediaType};base64,${encodeBase64(element.data)}"/>`;
664
+ if (element.kind === "raster-image") {
665
+ const rotation = element.rotationDegrees ? ` transform="rotate(${formatDecimal(element.rotationDegrees)} ${formatDecimal(element.frame.xMm + element.frame.widthMm / 2)} ${formatDecimal(element.frame.yMm + element.frame.heightMm / 2)})"` : "";
666
+ return `<image data-raster-resource="${escapeXml(element.resourceId)}"${rotation} x="${formatDecimal(element.frame.xMm)}" y="${formatDecimal(element.frame.yMm)}" width="${formatDecimal(element.frame.widthMm)}" height="${formatDecimal(element.frame.heightMm)}" opacity="${formatDecimal(element.opacity)}" preserveAspectRatio="none" href="data:${element.mediaType};base64,${encodeBase64(element.data)}"/>`;
667
+ }
665
668
  if (element.kind === "vector-symbol") {
666
669
  const transform = [
667
670
  `translate(${formatDecimal(element.position.xMm)} ${formatDecimal(element.position.yMm)})`,
@@ -1173,1298 +1176,1434 @@ function renderPointSymbolElements(symbol, vector, context) {
1173
1176
  };
1174
1177
  }
1175
1178
  //#endregion
1176
- //#region src/render-layers.ts
1177
- function geographicBounds(positions, longitudeReference) {
1178
- const longitudes = positions.map((position) => longitudeReference + ((position[0] - longitudeReference) % 360 + 540) % 360 - 180);
1179
- const latitudes = positions.map((position) => position[1]);
1180
- return {
1181
- minLongitude: Math.min(...longitudes),
1182
- minLatitude: Math.min(...latitudes),
1183
- maxLongitude: Math.max(...longitudes),
1184
- maxLatitude: Math.max(...latitudes)
1185
- };
1179
+ //#region src/raster-basemap.ts
1180
+ const TESSELLATION_TOLERANCE_MM = 1e-6;
1181
+ const LOW_DPI_THRESHOLD = 150;
1182
+ const DPI_ANISOTROPY_THRESHOLD = .01;
1183
+ function renderRasterBasemapLayers(basemap) {
1184
+ return basemap.layers.map((layer) => ({
1185
+ id: `raster-basemap-${layer.id}`,
1186
+ attributes: {
1187
+ "data-raster-layer": layer.id,
1188
+ "data-opacity": layer.opacity
1189
+ },
1190
+ graphics: layer.tiles.map((tile) => ({
1191
+ id: tile.id,
1192
+ elements: [{
1193
+ kind: "raster-image",
1194
+ mediaType: tile.mediaType,
1195
+ data: tile.data,
1196
+ frame: { ...tile.frame },
1197
+ opacity: layer.opacity,
1198
+ resourceId: `${layer.id}/${tile.id}`
1199
+ }]
1200
+ }))
1201
+ }));
1186
1202
  }
1187
- function boundsOverlap(left, right) {
1188
- return !(left.maxLongitude < right.minLongitude || left.minLongitude > right.maxLongitude || left.maxLatitude < right.minLatitude || left.minLatitude > right.maxLatitude);
1203
+ function requireStableId(value, label, ids) {
1204
+ if (typeof value !== "string" || value.trim() === "") throw new RangeError(`${label} must be a non-blank stable ID`);
1205
+ if (ids.has(value)) throw new RangeError(`Duplicate ${label.toLowerCase()}: ${value}`);
1206
+ ids.add(value);
1189
1207
  }
1190
- /**
1191
- * Liang-Barsky parametric clip. Each edge contributes a (coefficient, distance)
1192
- * pair; returns the surviving parameter range along the segment, or undefined
1193
- * when the segment lies entirely outside.
1194
- */
1195
- function clipParameterRange(edges) {
1196
- let entering = 0;
1197
- let leaving = 1;
1198
- for (const [coefficient, distance] of edges) {
1199
- if (coefficient === 0) {
1200
- if (distance < 0) return;
1201
- continue;
1208
+ function readUint32(bytes, offset, littleEndian = false) {
1209
+ if (offset < 0 || offset + 4 > bytes.length) throw new RangeError("Malformed image data");
1210
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(offset, littleEndian);
1211
+ }
1212
+ function readUint16(bytes, offset, littleEndian = false) {
1213
+ if (offset < 0 || offset + 2 > bytes.length) throw new RangeError("Malformed image data");
1214
+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint16(offset, littleEndian);
1215
+ }
1216
+ function ascii(bytes, offset, length) {
1217
+ if (offset < 0 || offset + length > bytes.length) throw new RangeError("Malformed image data");
1218
+ return String.fromCharCode(...bytes.subarray(offset, offset + length));
1219
+ }
1220
+ function inspectPng(bytes) {
1221
+ if (bytes.length < 33 || [
1222
+ 137,
1223
+ 80,
1224
+ 78,
1225
+ 71,
1226
+ 13,
1227
+ 10,
1228
+ 26,
1229
+ 10
1230
+ ].some((value, index) => bytes[index] !== value)) throw new RangeError("Malformed PNG image");
1231
+ if (readUint32(bytes, 8) !== 13 || ascii(bytes, 12, 4) !== "IHDR") throw new RangeError("Malformed PNG image: IHDR must be first");
1232
+ const width = readUint32(bytes, 16);
1233
+ const height = readUint32(bytes, 20);
1234
+ let offset = 8;
1235
+ let ended = false;
1236
+ while (offset + 12 <= bytes.length) {
1237
+ const length = readUint32(bytes, offset);
1238
+ const type = ascii(bytes, offset + 4, 4);
1239
+ const next = offset + 12 + length;
1240
+ if (next > bytes.length) throw new RangeError("Malformed PNG image chunk");
1241
+ if (type === "acTL") throw new RangeError("APNG images are not supported");
1242
+ offset = next;
1243
+ if (type === "IEND") {
1244
+ ended = true;
1245
+ break;
1202
1246
  }
1203
- const ratio = distance / coefficient;
1204
- if (coefficient < 0) entering = Math.max(entering, ratio);
1205
- else leaving = Math.min(leaving, ratio);
1206
- if (entering > leaving) return;
1207
1247
  }
1248
+ if (!ended || offset !== bytes.length || width === 0 || height === 0) throw new RangeError("Malformed PNG image");
1208
1249
  return {
1209
- entering,
1210
- leaving
1250
+ width,
1251
+ height
1211
1252
  };
1212
1253
  }
1213
- function clipSegmentToBounds(start, end, bounds) {
1214
- const deltaLongitude = end[0] - start[0];
1215
- const deltaLatitude = end[1] - start[1];
1216
- const range = clipParameterRange([
1217
- [-deltaLongitude, start[0] - bounds.minLongitude],
1218
- [deltaLongitude, bounds.maxLongitude - start[0]],
1219
- [-deltaLatitude, start[1] - bounds.minLatitude],
1220
- [deltaLatitude, bounds.maxLatitude - start[1]]
1221
- ]);
1222
- if (!range) return;
1223
- const positionAt = (ratio) => [start[0] + deltaLongitude * ratio, start[1] + deltaLatitude * ratio];
1224
- return [positionAt(range.entering), positionAt(range.leaving)];
1225
- }
1226
- function clipLineToBounds(positions, bounds) {
1227
- return positions.slice(1).flatMap((end, index) => {
1228
- const clipped = clipSegmentToBounds(positions[index], end, bounds);
1229
- return clipped ? [[...clipped]] : [];
1230
- });
1254
+ function readExifOrientation(bytes, start, length) {
1255
+ if (length < 6 || ascii(bytes, start, 6) !== "Exif\0\0") return void 0;
1256
+ if (length < 14) throw new RangeError("Malformed JPEG EXIF data");
1257
+ const tiff = start + 6;
1258
+ const byteOrder = ascii(bytes, tiff, 2);
1259
+ if (byteOrder !== "II" && byteOrder !== "MM") throw new RangeError("Malformed JPEG EXIF data");
1260
+ const littleEndian = byteOrder === "II";
1261
+ if (readUint16(bytes, tiff + 2, littleEndian) !== 42) throw new RangeError("Malformed JPEG EXIF data");
1262
+ const ifd = tiff + readUint32(bytes, tiff + 4, littleEndian);
1263
+ if (ifd + 2 > start + length) throw new RangeError("Malformed JPEG EXIF data");
1264
+ const entries = readUint16(bytes, ifd, littleEndian);
1265
+ for (let index = 0; index < entries; index += 1) {
1266
+ const entry = ifd + 2 + index * 12;
1267
+ if (entry + 12 > start + length) throw new RangeError("Malformed JPEG EXIF data");
1268
+ if (readUint16(bytes, entry, littleEndian) === 274) {
1269
+ if (readUint16(bytes, entry + 2, littleEndian) !== 3 || readUint32(bytes, entry + 4, littleEndian) !== 1) throw new RangeError("Malformed JPEG EXIF orientation");
1270
+ return readUint16(bytes, entry + 8, littleEndian);
1271
+ }
1272
+ }
1231
1273
  }
1232
- function clipRingToBounds(positions, bounds) {
1233
- const verticalIntersection = (longitude, start, end) => {
1234
- const ratio = (longitude - start[0]) / (end[0] - start[0]);
1235
- return [longitude, start[1] + (end[1] - start[1]) * ratio];
1236
- };
1237
- const horizontalIntersection = (latitude, start, end) => {
1238
- const ratio = (latitude - start[1]) / (end[1] - start[1]);
1239
- return [start[0] + (end[0] - start[0]) * ratio, latitude];
1240
- };
1241
- const boundaries = [
1242
- {
1243
- inside: (position) => position[0] >= bounds.minLongitude,
1244
- intersection: (start, end) => verticalIntersection(bounds.minLongitude, start, end)
1245
- },
1246
- {
1247
- inside: (position) => position[0] <= bounds.maxLongitude,
1248
- intersection: (start, end) => verticalIntersection(bounds.maxLongitude, start, end)
1249
- },
1250
- {
1251
- inside: (position) => position[1] >= bounds.minLatitude,
1252
- intersection: (start, end) => horizontalIntersection(bounds.minLatitude, start, end)
1253
- },
1254
- {
1255
- inside: (position) => position[1] <= bounds.maxLatitude,
1256
- intersection: (start, end) => horizontalIntersection(bounds.maxLatitude, start, end)
1274
+ function inspectJpeg(bytes) {
1275
+ if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216 || bytes.at(-2) !== 255 || bytes.at(-1) !== 217) throw new RangeError("Malformed JPEG image");
1276
+ let offset = 2;
1277
+ let dimensions;
1278
+ let sawScan = false;
1279
+ while (offset < bytes.length - 2) {
1280
+ if (bytes[offset] !== 255) throw new RangeError("Malformed JPEG marker");
1281
+ while (bytes[offset] === 255) offset += 1;
1282
+ const marker = bytes[offset++];
1283
+ if (marker === 217) break;
1284
+ if (marker === 218) {
1285
+ const segmentLength = readUint16(bytes, offset);
1286
+ if (segmentLength < 2 || offset + segmentLength > bytes.length - 2) throw new RangeError("Malformed JPEG scan header");
1287
+ sawScan = true;
1288
+ break;
1257
1289
  }
1258
- ];
1259
- const first = positions[0];
1260
- const last = positions.at(-1);
1261
- let clipped = first && last && first[0] === last[0] && first[1] === last[1] ? positions.slice(0, -1) : [...positions];
1262
- for (const boundary of boundaries) {
1263
- const input = clipped;
1264
- clipped = [];
1265
- let start = input.at(-1);
1266
- for (const end of input) {
1267
- if (!start) break;
1268
- if (boundary.inside(end)) {
1269
- if (!boundary.inside(start)) clipped.push(boundary.intersection(start, end));
1270
- clipped.push(end);
1271
- } else if (boundary.inside(start)) clipped.push(boundary.intersection(start, end));
1272
- start = end;
1290
+ if (marker === 1 || marker >= 208 && marker <= 215) continue;
1291
+ const segmentLength = readUint16(bytes, offset);
1292
+ if (segmentLength < 2 || offset + segmentLength > bytes.length) throw new RangeError("Malformed JPEG segment");
1293
+ const dataStart = offset + 2;
1294
+ const dataLength = segmentLength - 2;
1295
+ if (marker === 225) {
1296
+ const orientation = readExifOrientation(bytes, dataStart, dataLength);
1297
+ if (orientation !== void 0 && orientation !== 1) throw new RangeError(`JPEG EXIF orientation ${orientation} is not supported`);
1273
1298
  }
1299
+ if (marker === 192 || marker === 194) {
1300
+ if (dataLength < 6) throw new RangeError("Malformed JPEG dimensions");
1301
+ dimensions = {
1302
+ height: readUint16(bytes, dataStart + 1),
1303
+ width: readUint16(bytes, dataStart + 3)
1304
+ };
1305
+ } else if (marker >= 192 && marker <= 207 && ![
1306
+ 196,
1307
+ 200,
1308
+ 204
1309
+ ].includes(marker)) throw new RangeError("Only baseline and progressive JPEG images are supported");
1310
+ offset += segmentLength;
1274
1311
  }
1275
- if (clipped.length > 0) clipped.push([...clipped[0]]);
1276
- return clipped;
1312
+ if (!dimensions || dimensions.width === 0 || dimensions.height === 0 || !sawScan) throw new RangeError("Malformed JPEG image: dimensions are missing");
1313
+ return dimensions;
1277
1314
  }
1278
- function clipGeometryToBounds(geometry, bounds) {
1279
- if (geometry.type === "Point") return;
1280
- if (geometry.type === "LineString") {
1281
- const lines = clipLineToBounds(geometry.coordinates, bounds);
1282
- if (lines.length === 0) return;
1283
- return lines.length === 1 ? {
1284
- type: "LineString",
1285
- coordinates: lines[0]
1286
- } : {
1287
- type: "MultiLineString",
1288
- coordinates: lines
1289
- };
1290
- }
1291
- if (geometry.type === "MultiLineString") {
1292
- const lines = geometry.coordinates.flatMap((line) => clipLineToBounds(line, bounds));
1293
- return lines.length === 0 ? void 0 : {
1294
- type: "MultiLineString",
1295
- coordinates: lines
1296
- };
1297
- }
1298
- if (geometry.type === "Polygon") {
1299
- const rings = geometry.coordinates.map((ring) => clipRingToBounds(ring, bounds)).filter((ring) => ring.length >= 4);
1300
- return rings.length === 0 ? void 0 : {
1301
- type: "Polygon",
1302
- coordinates: rings
1303
- };
1315
+ function inspectImage(tile) {
1316
+ if (!(tile.data instanceof Uint8Array) || tile.data.length === 0) throw new RangeError(`Raster tile ${tile.id} image bytes must be non-empty`);
1317
+ if (!Number.isInteger(tile.pixelWidth) || tile.pixelWidth <= 0 || !Number.isInteger(tile.pixelHeight) || tile.pixelHeight <= 0) throw new RangeError(`Raster tile ${tile.id} pixel dimensions must be positive integers`);
1318
+ const actual = tile.mediaType === "image/png" ? inspectPng(tile.data) : tile.mediaType === "image/jpeg" ? inspectJpeg(tile.data) : void 0;
1319
+ if (!actual) throw new RangeError(`Raster tile ${tile.id} media type is not supported`);
1320
+ if (actual.width !== tile.pixelWidth || actual.height !== tile.pixelHeight) {
1321
+ const format = tile.mediaType === "image/png" ? "PNG" : "JPEG";
1322
+ throw new RangeError(`Raster tile ${tile.id} declared dimensions ${tile.pixelWidth}x${tile.pixelHeight} do not match ${format} dimensions ${actual.width}x${actual.height}`);
1304
1323
  }
1305
- return geometry;
1306
1324
  }
1307
- function geometryPositions(geometry) {
1308
- switch (geometry.type) {
1309
- case "Point": return [geometry.coordinates];
1310
- case "MultiPoint":
1311
- case "LineString": return geometry.coordinates;
1312
- case "MultiLineString":
1313
- case "Polygon": return geometry.coordinates.flat();
1314
- case "MultiPolygon": return geometry.coordinates.flat(2);
1315
- case "GeometryCollection": return geometry.geometries.flatMap(geometryPositions);
1316
- default: return assertNever(geometry);
1325
+ function clustered(values) {
1326
+ const sorted = [...values].sort((left, right) => left - right);
1327
+ const result = [];
1328
+ for (const value of sorted) if (result.length === 0 || value - result[result.length - 1] > TESSELLATION_TOLERANCE_MM) result.push(value);
1329
+ return result;
1330
+ }
1331
+ function validateTessellation(layer, frame) {
1332
+ const right = frame.xMm + frame.widthMm;
1333
+ const bottom = frame.yMm + frame.heightMm;
1334
+ for (const tile of layer.tiles) {
1335
+ const rectangle = tile.frame;
1336
+ if (!Number.isFinite(rectangle.xMm) || !Number.isFinite(rectangle.yMm) || !Number.isFinite(rectangle.widthMm) || !Number.isFinite(rectangle.heightMm) || rectangle.widthMm <= 0 || rectangle.heightMm <= 0 || rectangle.xMm < frame.xMm - TESSELLATION_TOLERANCE_MM || rectangle.yMm < frame.yMm - TESSELLATION_TOLERANCE_MM || rectangle.xMm + rectangle.widthMm > right + TESSELLATION_TOLERANCE_MM || rectangle.yMm + rectangle.heightMm > bottom + TESSELLATION_TOLERANCE_MM) throw new RangeError(`Raster layer ${layer.id} must tessellate the complete map frame`);
1337
+ }
1338
+ const xs = clustered([
1339
+ frame.xMm,
1340
+ right,
1341
+ ...layer.tiles.flatMap((tile) => [tile.frame.xMm, tile.frame.xMm + tile.frame.widthMm])
1342
+ ]);
1343
+ const ys = clustered([
1344
+ frame.yMm,
1345
+ bottom,
1346
+ ...layer.tiles.flatMap((tile) => [tile.frame.yMm, tile.frame.yMm + tile.frame.heightMm])
1347
+ ]);
1348
+ for (let xIndex = 0; xIndex < xs.length - 1; xIndex += 1) for (let yIndex = 0; yIndex < ys.length - 1; yIndex += 1) {
1349
+ const x = (xs[xIndex] + xs[xIndex + 1]) / 2;
1350
+ const y = (ys[yIndex] + ys[yIndex + 1]) / 2;
1351
+ if (x < frame.xMm || x > right || y < frame.yMm || y > bottom) continue;
1352
+ if (layer.tiles.filter((tile) => x >= tile.frame.xMm - TESSELLATION_TOLERANCE_MM && x <= tile.frame.xMm + tile.frame.widthMm + TESSELLATION_TOLERANCE_MM && y >= tile.frame.yMm - TESSELLATION_TOLERANCE_MM && y <= tile.frame.yMm + tile.frame.heightMm + TESSELLATION_TOLERANCE_MM).length !== 1) throw new RangeError(`Raster layer ${layer.id} must tessellate the complete map frame`);
1317
1353
  }
1318
1354
  }
1319
- function projectionRangeError(positions, context) {
1320
- return positions.some((position) => {
1321
- try {
1322
- geographicLibGridProjection.forward(context.crs, position);
1323
- return false;
1324
- } catch (error) {
1325
- return isGridProjectionRangeError(error);
1326
- }
1355
+ function validateAttribution(attribution) {
1356
+ return attribution.map((entry) => {
1357
+ if (typeof entry.text !== "string" || entry.text.trim() === "") throw new RangeError("Raster attribution text must be non-blank");
1358
+ if (typeof entry.required !== "boolean") throw new RangeError("Raster attribution requiredness must be explicit");
1359
+ return {
1360
+ text: entry.text,
1361
+ required: entry.required
1362
+ };
1327
1363
  });
1328
1364
  }
1329
- const frameBoundsCache = /* @__PURE__ */ new WeakMap();
1330
- /** The footprint ring is fixed for a render pass, so its bounds are cached. */
1331
- function frameGeographicBounds(context) {
1332
- const cached = frameBoundsCache.get(context.footprintRing);
1333
- if (cached) return cached;
1334
- const longitudeReference = context.footprintRing[0][0];
1335
- const bounds = geographicBounds(context.footprintRing, longitudeReference);
1336
- frameBoundsCache.set(context.footprintRing, bounds);
1337
- return bounds;
1338
- }
1339
- function positiveModulo(value, divisor) {
1340
- return (value % divisor + divisor) % divisor;
1341
- }
1342
- function patternPaintToScene(paint, color) {
1343
- return {
1344
- ...paint.fill ? { fillColor: color } : {},
1345
- ...paint.stroke ? { stroke: {
1346
- color,
1347
- widthMm: paint.stroke.width * MILLIMETRES_PER_CSS_PIXEL,
1348
- lineCap: paint.stroke.lineCap,
1349
- dashMm: (paint.stroke.dash ?? []).map((value) => value * MILLIMETRES_PER_CSS_PIXEL)
1350
- } } : {}
1351
- };
1352
- }
1353
- function patternCommandToScene(command, color) {
1354
- const point = ([x, y]) => ({
1355
- xMm: x * MILLIMETRES_PER_CSS_PIXEL,
1356
- yMm: y * MILLIMETRES_PER_CSS_PIXEL
1357
- });
1358
- if (command.type === "circle") return {
1359
- type: "circle",
1360
- center: point(command.center),
1361
- radiusMm: command.radius * MILLIMETRES_PER_CSS_PIXEL,
1362
- paint: patternPaintToScene(command.paint, color)
1363
- };
1364
- return {
1365
- type: "path",
1366
- operations: command.operations.map((operation) => {
1367
- if (operation.type === "close") return operation;
1368
- if (operation.type === "cubic") return {
1369
- type: "cubic",
1370
- control1: point(operation.control1),
1371
- control2: point(operation.control2),
1372
- to: point(operation.to)
1373
- };
1365
+ function resolveRasterBasemap(basemap, frame) {
1366
+ if (basemap.layers.length === 0) throw new RangeError("A raster basemap requires at least one layer");
1367
+ const layerIds = /* @__PURE__ */ new Set();
1368
+ const tileIds = /* @__PURE__ */ new Set();
1369
+ const attributionTexts = /* @__PURE__ */ new Set();
1370
+ const warnings = [];
1371
+ const allAttribution = [];
1372
+ const layers = basemap.layers.map((layer) => {
1373
+ requireStableId(layer.id, "Raster layer ID", layerIds);
1374
+ if (!Number.isFinite(layer.opacity) || layer.opacity < 0 || layer.opacity > 1) throw new RangeError(`Raster layer ${layer.id} opacity must be from 0 through 1`);
1375
+ if (layer.tiles.length === 0) throw new RangeError(`Raster layer ${layer.id} requires at least one tile`);
1376
+ const attribution = validateAttribution(layer.attribution).filter((entry) => {
1377
+ if (attributionTexts.has(entry.text)) return false;
1378
+ attributionTexts.add(entry.text);
1379
+ return true;
1380
+ });
1381
+ allAttribution.push(...attribution);
1382
+ for (const tile of layer.tiles) {
1383
+ requireStableId(tile.id, "Raster tile ID", tileIds);
1384
+ inspectImage(tile);
1385
+ }
1386
+ validateTessellation(layer, frame);
1387
+ const tiles = layer.tiles.map((tile) => {
1388
+ const effectiveHorizontalDpi = tile.pixelWidth * 25.4 / tile.frame.widthMm;
1389
+ const effectiveVerticalDpi = tile.pixelHeight * 25.4 / tile.frame.heightMm;
1390
+ if (effectiveHorizontalDpi < LOW_DPI_THRESHOLD || effectiveVerticalDpi < LOW_DPI_THRESHOLD) warnings.push({
1391
+ code: "low-raster-dpi",
1392
+ layerId: layer.id,
1393
+ tileId: tile.id,
1394
+ effectiveHorizontalDpi,
1395
+ effectiveVerticalDpi,
1396
+ thresholdDpi: LOW_DPI_THRESHOLD
1397
+ });
1398
+ const relativeDifference = Math.abs(effectiveHorizontalDpi - effectiveVerticalDpi) / Math.max(effectiveHorizontalDpi, effectiveVerticalDpi);
1399
+ if (relativeDifference > DPI_ANISOTROPY_THRESHOLD) warnings.push({
1400
+ code: "raster-dpi-anisotropy",
1401
+ layerId: layer.id,
1402
+ tileId: tile.id,
1403
+ relativeDifference
1404
+ });
1374
1405
  return {
1375
- type: operation.type,
1376
- to: point(operation.to)
1406
+ id: tile.id,
1407
+ mediaType: tile.mediaType,
1408
+ pixelWidth: tile.pixelWidth,
1409
+ pixelHeight: tile.pixelHeight,
1410
+ frame: { ...tile.frame },
1411
+ effectiveHorizontalDpi,
1412
+ effectiveVerticalDpi
1377
1413
  };
1378
- }),
1379
- paint: patternPaintToScene(command.paint, color)
1414
+ });
1415
+ return {
1416
+ resolved: {
1417
+ id: layer.id,
1418
+ opacity: layer.opacity,
1419
+ tiles: [...layer.tiles]
1420
+ },
1421
+ metadata: {
1422
+ id: layer.id,
1423
+ opacity: layer.opacity,
1424
+ attribution,
1425
+ tiles
1426
+ }
1427
+ };
1428
+ });
1429
+ return {
1430
+ layers: layers.map((layer) => layer.resolved),
1431
+ metadata: { layers: layers.map((layer) => layer.metadata) },
1432
+ warnings,
1433
+ attribution: allAttribution
1380
1434
  };
1381
1435
  }
1382
- function registerPattern(pattern, color, context) {
1383
- const existing = context.patterns.find((resource) => resource.identity.pattern === pattern && resource.identity.color === color);
1384
- if (existing) return existing.identity.id;
1385
- const definition = getFillPatternDefinition(pattern);
1386
- const tileWidthMm = definition.tile.width * MILLIMETRES_PER_CSS_PIXEL;
1387
- const tileHeightMm = definition.tile.height * MILLIMETRES_PER_CSS_PIXEL;
1388
- const patternFrame = {
1389
- frame: context.frame,
1390
- center: context.center,
1391
- projectedMetresPerMillimetre: context.patternProjectedMetresPerMillimetre
1392
- };
1393
- const projectedOriginXMm = eastingToMillimetres(0, patternFrame);
1394
- const projectedOriginYMm = northingToMillimetres(0, patternFrame);
1395
- const resource = {
1396
- identity: {
1397
- id: `sheet-pattern-${context.patterns.length}`,
1398
- pattern,
1399
- color,
1400
- tileWidthMm,
1401
- tileHeightMm,
1402
- phaseXMm: positiveModulo(projectedOriginXMm, tileWidthMm),
1403
- phaseYMm: positiveModulo(projectedOriginYMm, tileHeightMm)
1404
- },
1405
- commands: definition.commands.map((command) => patternCommandToScene(command, color))
1436
+ //#endregion
1437
+ //#region src/note.ts
1438
+ const DEFAULT_DPI = 300;
1439
+ const MILLIMETRES_PER_INCH = 25.4;
1440
+ /** Longest side of a printed Note, which keeps it within what browsers' canvases allow. */
1441
+ const MAX_RASTER_PIXELS = 8192;
1442
+ /**
1443
+ * Rasterises every Note in `request.layers` at print density, in a browser, and
1444
+ * returns the capability to pass as `notes`.
1445
+ *
1446
+ * @throws if a Note's image can't be resolved: a sheet must not silently lose a picture.
1447
+ */
1448
+ async function prepareMapSheetNotes(request, options) {
1449
+ const dpi = options.dpi ?? DEFAULT_DPI;
1450
+ const scale = request.scaleDenominator;
1451
+ requirePositiveFinite(dpi, "Note dpi");
1452
+ requirePositiveFinite(scale, "scaleDenominator");
1453
+ const notes = (request.layers ?? []).flatMap((layer) => layer.graphics.map((authored) => authored.graphic).filter((graphic) => graphic.kind === "note"));
1454
+ const rasters = /* @__PURE__ */ new Map();
1455
+ for (const note of notes) try {
1456
+ validateNote(note);
1457
+ const { canvas, heightEm } = await options.notes.renderCanvas(note, { pxPerEm: printDensity(note, scale, dpi) });
1458
+ rasters.set(note.id, {
1459
+ url: canvas.toDataURL("image/png"),
1460
+ heightEm
1461
+ });
1462
+ } catch (error) {
1463
+ throw new Error(`Cannot render Graphic "${note.id}": ${String(error)}`, { cause: error });
1464
+ }
1465
+ return { rasters: { resolve: (noteId) => rasters.get(noteId) } };
1466
+ }
1467
+ /** Pixels per em at `dpi`. Web Mercator metres shrink to ground metres by the cosine of latitude. */
1468
+ function printDensity(note, scale, dpi) {
1469
+ const latitude = note.position[1] * Math.PI / 180;
1470
+ const density = note.emSize.value * Math.cos(latitude) / scale * 1e3 / MILLIMETRES_PER_INCH * dpi;
1471
+ return Math.max(1, Math.min(density, MAX_RASTER_PIXELS / note.width));
1472
+ }
1473
+ const EARTH_RADIUS = 6378137;
1474
+ function toMercator([longitude, latitude]) {
1475
+ const phi = latitude * Math.PI / 180;
1476
+ return [EARTH_RADIUS * longitude * Math.PI / 180, EARTH_RADIUS * Math.log(Math.tan(Math.PI / 4 + phi / 2))];
1477
+ }
1478
+ function fromMercator([x, y]) {
1479
+ return [x / EARTH_RADIUS * (180 / Math.PI), (2 * Math.atan(Math.exp(y / EARTH_RADIUS)) - Math.PI / 2) * (180 / Math.PI)];
1480
+ }
1481
+ function validateNote(note) {
1482
+ if (note.schemaVersion !== void 0 && note.schemaVersion !== 1) throw new TypeError("Note schemaVersion must be 1");
1483
+ if (note.emSize?.unit !== "meters") throw new TypeError("Note emSize unit must be \"meters\"");
1484
+ requirePositiveFinite(note.emSize.value, "Note emSize");
1485
+ requirePositiveFinite(note.width, "Note width");
1486
+ if (!Number.isFinite(note.rotation)) throw new RangeError("Note rotation must be finite");
1487
+ if (!Number.isFinite(note.style?.opacity ?? 1)) throw new RangeError("Note opacity must be finite");
1488
+ }
1489
+ /** Clamped to `[0, 1]` like the map's opacity (ADR-0040), so a Note that displays also prints. */
1490
+ function noteOpacity(note) {
1491
+ return Math.max(0, Math.min(1, note.style?.opacity ?? 1));
1492
+ }
1493
+ function scenePointOf(position, context) {
1494
+ return projectedToScenePoint(geographicLibGridProjection.forward(context.crs, position), context);
1495
+ }
1496
+ /**
1497
+ * Places the Note like the map does: the box is laid out in Web Mercator metres
1498
+ * around its centre, rotated clockwise from north. The sheet maps that box with
1499
+ * the similarity the projection gives at the centre-to-edge vector, so scale and
1500
+ * rotation (including grid convergence) match the map's footprint.
1501
+ */
1502
+ function notePlacement(note, context) {
1503
+ const center = toMercator(note.position);
1504
+ const halfWidthMetres = note.width * note.emSize.value / 2;
1505
+ const edge = [center[0] + halfWidthMetres * Math.cos(note.rotation), center[1] - halfWidthMetres * Math.sin(note.rotation)];
1506
+ const position = scenePointOf(note.position, context);
1507
+ const edgePoint = scenePointOf(fromMercator(edge), context);
1508
+ const dx = edgePoint.xMm - position.xMm;
1509
+ const dy = edgePoint.yMm - position.yMm;
1510
+ return {
1511
+ position,
1512
+ scaleMmPerEm: Math.hypot(dx, dy) / (note.width / 2),
1513
+ rotationDegrees: Math.atan2(dy, dx) * 180 / Math.PI
1406
1514
  };
1407
- context.patterns.push(resource);
1408
- return resource.identity.id;
1409
1515
  }
1410
- function requireIdentifier(value, name) {
1411
- if (typeof value !== "string" || value.length === 0) throw new TypeError(`${name} is required`);
1516
+ function decodePng(noteId, url) {
1517
+ const comma = url.indexOf(",");
1518
+ if (!/^data:image\/png(?:;[^;,]*)*;base64$/i.test(url.slice(0, Math.max(comma, 0)))) throw new Error(`Note "${noteId}": its raster must be a base64 PNG data URL`);
1519
+ const decoded = globalThis.atob(url.slice(comma + 1));
1520
+ const data = Uint8Array.from(decoded, (character) => character.charCodeAt(0));
1521
+ inspectPng(data);
1522
+ return data;
1412
1523
  }
1413
- function requireFiniteNonNegative(value, name) {
1414
- if (!Number.isFinite(value) || value < 0) throw new RangeError(`${name} must be a finite non-negative number`);
1524
+ /**
1525
+ * Renders a Note as one rotated raster element, placed under the Note's ground
1526
+ * position, scale and rotation.
1527
+ *
1528
+ * @throws if the Note is malformed or has no prepared raster.
1529
+ */
1530
+ function renderNoteElements(note, capability, context) {
1531
+ validateNote(note);
1532
+ const raster = capability.rasters.resolve(note.id);
1533
+ if (!raster) throw new Error(`Note "${note.id}" has no prepared raster`);
1534
+ requirePositiveFinite(raster.heightEm, "Note raster heightEm");
1535
+ const placement = notePlacement(note, context);
1536
+ const widthMm = note.width * placement.scaleMmPerEm;
1537
+ const heightMm = raster.heightEm * placement.scaleMmPerEm;
1538
+ return { elements: [{
1539
+ kind: "raster-image",
1540
+ mediaType: "image/png",
1541
+ data: decodePng(note.id, raster.url),
1542
+ frame: {
1543
+ xMm: placement.position.xMm - widthMm / 2,
1544
+ yMm: placement.position.yMm - heightMm / 2,
1545
+ widthMm,
1546
+ heightMm
1547
+ },
1548
+ opacity: noteOpacity(note),
1549
+ resourceId: `note:${note.id}`,
1550
+ compressInPdf: true,
1551
+ rotationDegrees: placement.rotationDegrees
1552
+ }] };
1415
1553
  }
1416
- function resolvePortrayal(input) {
1417
- const strokeWidthCssPixels = input?.strokeWidthCssPixels ?? DEFAULT_STROKE_WIDTH_CSS_PIXELS;
1418
- requirePositiveFinite(strokeWidthCssPixels, "Stroke width");
1419
- const strokeDashCssPixels = input?.strokeDashCssPixels ?? DEFAULT_STROKE_DASH_CSS_PIXELS;
1420
- strokeDashCssPixels.forEach((value) => requireFiniteNonNegative(value, "Stroke dash"));
1421
- const labelHeightCssPixels = input?.labelHeightCssPixels ?? DEFAULT_LABEL_HEIGHT_CSS_PIXELS;
1422
- requirePositiveFinite(labelHeightCssPixels, "Label height");
1423
- const labelSizeClampCssPixels = input?.labelSizeClampCssPixels ?? DEFAULT_LABEL_SIZE_BAND;
1424
- requireFiniteNonNegative(labelSizeClampCssPixels.min, "Label clamp minimum");
1425
- requireFiniteNonNegative(labelSizeClampCssPixels.max, "Label clamp maximum");
1426
- const symbolColor = input?.symbolColor ?? DEFAULT_PORTRAYAL.symbolColor;
1427
- if (typeof symbolColor !== "string" || symbolColor.length === 0) throw new TypeError("Symbol color is required");
1554
+ //#endregion
1555
+ //#region src/render-layers.ts
1556
+ function geographicBounds(positions, longitudeReference) {
1557
+ const longitudes = positions.map((position) => longitudeReference + ((position[0] - longitudeReference) % 360 + 540) % 360 - 180);
1558
+ const latitudes = positions.map((position) => position[1]);
1428
1559
  return {
1429
- symbolColor,
1430
- strokeWidthCssPixels,
1431
- strokeDashCssPixels,
1432
- lineCap: input?.lineCap ?? DEFAULT_LINE_CAP,
1433
- lineJoin: input?.lineJoin ?? DEFAULT_LINE_JOIN,
1434
- labelHeightCssPixels,
1435
- labelSizeClampCssPixels,
1436
- labelSizeBand: {
1437
- ...labelSizeClampCssPixels,
1438
- belowMin: "pin"
1439
- },
1440
- highlightAppearance: input?.highlightAppearance
1560
+ minLongitude: Math.min(...longitudes),
1561
+ minLatitude: Math.min(...latitudes),
1562
+ maxLongitude: Math.max(...longitudes),
1563
+ maxLatitude: Math.max(...latitudes)
1441
1564
  };
1442
1565
  }
1443
- function toScenePoint(position, context) {
1444
- return projectedToScenePoint(geographicLibGridProjection.forward(context.crs, position), context);
1445
- }
1446
- function pathFromPositions(positions, closed, properties, portrayal, context) {
1447
- if (positions.length < 2) throw new Error("A document path requires at least two positions");
1448
- const style = properties.style;
1449
- const strokeWidthCssPixels = style?.strokeWidth ?? portrayal.strokeWidthCssPixels;
1450
- requireFiniteNonNegative(strokeWidthCssPixels, "Stroke width");
1451
- const strokeDashCssPixels = style?.strokeDash ?? portrayal.strokeDashCssPixels;
1452
- strokeDashCssPixels.forEach((value) => requireFiniteNonNegative(value, "Stroke dash"));
1453
- const fillPattern = style?.fillPattern;
1454
- const fillColor = style?.fillColor;
1455
- const fillPatternId = fillPattern && fillPattern !== "solid" && fillColor ? registerPattern(fillPattern, fillColor, context) : void 0;
1456
- return {
1457
- kind: "path",
1458
- points: positions.map((position) => toScenePoint(position, context)),
1459
- ...closed ? { closed: true } : {},
1460
- strokeColor: style?.strokeColor ?? portrayal.symbolColor,
1461
- strokeWidthMm: strokeWidthCssPixels * MILLIMETRES_PER_CSS_PIXEL,
1462
- strokeDashMm: strokeDashCssPixels.map((value) => value * MILLIMETRES_PER_CSS_PIXEL),
1463
- lineCap: portrayal.lineCap,
1464
- lineJoin: portrayal.lineJoin,
1465
- ...fillColor ? { fillColor } : {},
1466
- ...fillPatternId ? { fillPatternId } : {}
1467
- };
1468
- }
1469
- function resolveTextSizeCssPixels(properties, portrayal, constructionMetersPerCssPixel) {
1470
- if (properties.textSizePixels === void 0 && properties.textSizeMeters === void 0) return portrayal.labelHeightCssPixels;
1471
- const { min, max } = portrayal.labelSizeClampCssPixels;
1472
- const band = {
1473
- textSizeMinPixels: Math.min(min, max),
1474
- textSizeMaxPixels: Math.max(min, max)
1475
- };
1476
- return resolveTextAppearance({
1477
- ...properties,
1478
- ...band
1479
- }, constructionMetersPerCssPixel, { pinBelowMinimum: true })?.sizePixels;
1566
+ function boundsOverlap(left, right) {
1567
+ return !(left.maxLongitude < right.minLongitude || left.minLongitude > right.maxLongitude || left.maxLatitude < right.minLatitude || left.minLatitude > right.maxLatitude);
1480
1568
  }
1481
1569
  /**
1482
- * The scene point at `(x, y)` mm in a frame at `origin` rotated
1483
- * `rotationDegrees` clockwise (scene y grows downward). Text, its screen-space
1484
- * offset (`labelTextOffsetEms`, ADR-0068) and vector symbols all use it, so
1485
- * they share one rotation convention.
1570
+ * Liang-Barsky parametric clip. Each edge contributes a (coefficient, distance)
1571
+ * pair; returns the surviving parameter range along the segment, or undefined
1572
+ * when the segment lies entirely outside.
1486
1573
  */
1487
- function pointInRotatedFrame(origin, rotationDegrees, x, y) {
1488
- const radians = rotationDegrees * Math.PI / 180;
1489
- const cos = Math.cos(radians);
1490
- const sin = Math.sin(radians);
1491
- return {
1492
- xMm: origin.xMm + x * cos - y * sin,
1493
- yMm: origin.yMm + x * sin + y * cos
1494
- };
1495
- }
1496
- function textFromFeature(feature, portrayal, context, constructionMetersPerCssPixel) {
1497
- if (feature.geometry.type !== "Point" || feature.properties.text === void 0) return;
1498
- const fontSizeCssPixels = resolveTextSizeCssPixels(feature.properties, portrayal, constructionMetersPerCssPixel);
1499
- if (fontSizeCssPixels === void 0) return;
1500
- requirePositiveFinite(fontSizeCssPixels, "Text size");
1501
- const style = feature.properties.textStyle ?? "regular";
1502
- const text = normalizeLogicalText(feature.properties.text, style);
1503
- const measured = measureOpenSans({
1504
- text,
1505
- style,
1506
- sizeCssPixels: fontSizeCssPixels
1507
- });
1508
- const fontSizeMm = fontSizeCssPixels * MILLIMETRES_PER_CSS_PIXEL;
1509
- const rotationDegrees = (Math.PI - (feature.properties.rotation ?? Math.PI)) * 180 / Math.PI;
1510
- const anchor = toScenePoint(feature.geometry.coordinates, context);
1511
- const offsetEms = labelTextOffsetEms(feature.properties);
1574
+ function clipParameterRange(edges) {
1575
+ let entering = 0;
1576
+ let leaving = 1;
1577
+ for (const [coefficient, distance] of edges) {
1578
+ if (coefficient === 0) {
1579
+ if (distance < 0) return;
1580
+ continue;
1581
+ }
1582
+ const ratio = distance / coefficient;
1583
+ if (coefficient < 0) entering = Math.max(entering, ratio);
1584
+ else leaving = Math.min(leaving, ratio);
1585
+ if (entering > leaving) return;
1586
+ }
1512
1587
  return {
1513
- kind: "text",
1514
- position: offsetEms ? pointInRotatedFrame(anchor, rotationDegrees, offsetEms[0] * fontSizeMm, offsetEms[1] * fontSizeMm) : anchor,
1515
- text,
1516
- rotationDegrees,
1517
- fontSizeMm,
1518
- widthMm: measured.widthCssPixels * MILLIMETRES_PER_CSS_PIXEL,
1519
- heightMm: measured.heightCssPixels * MILLIMETRES_PER_CSS_PIXEL,
1520
- lineHeightMm: fontSizeMm * OPEN_SANS_LINE_HEIGHT_FACTOR,
1521
- anchor: feature.properties.textAnchor === "start" ? "start" : feature.properties.textAnchor === "end" ? "end" : "middle",
1522
- justify: feature.properties.textJustify ?? "center",
1523
- color: feature.properties.style?.strokeColor ?? portrayal.symbolColor,
1524
- background: feature.properties.textBackground === true,
1525
- ...style === "italic" ? { fontStyle: "italic" } : {},
1526
- ...style === "light" ? { fontWeight: 300 } : {},
1527
- ...feature.properties.textHalo && feature.properties.textHaloColor ? {
1528
- haloColor: feature.properties.textHaloColor,
1529
- haloWidthMm: MILLIMETRES_PER_CSS_PIXEL
1530
- } : {}
1588
+ entering,
1589
+ leaving
1531
1590
  };
1532
1591
  }
1533
- /**
1534
- * One Highlight band stroked along each path a highlighted line or area part
1535
- * drew: the same geometry as one solid stroke in the resolved
1536
- * `highlightColor`, never filled, so an area is cased along its outline only
1537
- * and a transparent stroke is still cased. Glow bands carry their opacity, so
1538
- * SVG and PDF print them alike.
1539
- */
1540
- function highlightBandPaths(band, parts) {
1541
- return parts.flatMap((part) => part.kind === "path" ? [{
1542
- kind: "path",
1543
- points: part.points,
1544
- ...part.closed ? { closed: true } : {},
1545
- strokeColor: band.color,
1546
- strokeWidthMm: band.width * MILLIMETRES_PER_CSS_PIXEL,
1547
- ...band.opacity < 1 ? { strokeOpacity: band.opacity } : {},
1548
- strokeDashMm: [],
1549
- lineCap: "round",
1550
- lineJoin: "round"
1551
- }] : []);
1552
- }
1553
- function elementsFromGeometry(feature, portrayal, context, constructionMetersPerCssPixel) {
1554
- const text = textFromFeature(feature, portrayal, context, constructionMetersPerCssPixel);
1555
- if (text) return [text];
1556
- if (feature.geometry.type === "Point" && feature.properties.text !== void 0) return [];
1557
- const path = (positions, closed = false) => pathFromPositions(positions, closed, feature.properties, portrayal, context);
1558
- switch (feature.geometry.type) {
1559
- case "LineString": return [path(feature.geometry.coordinates)];
1560
- case "MultiLineString": return feature.geometry.coordinates.map((line) => path(line));
1561
- case "Polygon":
1562
- if (feature.geometry.coordinates.length !== 1) throw new Error("Polygon holes are not representable in this milestone");
1563
- return [path(feature.geometry.coordinates[0], true)];
1564
- case "MultiPolygon":
1565
- case "Point":
1566
- case "MultiPoint": throw new Error(`${feature.geometry.type} features are not representable in this milestone`);
1567
- case "GeometryCollection": throw new Error("GeometryCollection features cannot be represented by this document renderer");
1568
- default: return assertNever(feature.geometry);
1569
- }
1570
- }
1571
- function pointInside(point, frame) {
1572
- return point.xMm >= frame.xMm && point.xMm <= frame.xMm + frame.widthMm && point.yMm >= frame.yMm && point.yMm <= frame.yMm + frame.heightMm;
1573
- }
1574
- function segmentIntersectsFrame(start, end, frame) {
1575
- if (pointInside(start, frame) || pointInside(end, frame)) return true;
1576
- const left = frame.xMm;
1577
- const right = left + frame.widthMm;
1578
- const top = frame.yMm;
1579
- const bottom = top + frame.heightMm;
1580
- const deltaX = end.xMm - start.xMm;
1581
- const deltaY = end.yMm - start.yMm;
1582
- return clipParameterRange([
1583
- [-deltaX, start.xMm - left],
1584
- [deltaX, right - start.xMm],
1585
- [-deltaY, start.yMm - top],
1586
- [deltaY, bottom - start.yMm]
1587
- ]) !== void 0;
1592
+ function clipSegmentToBounds(start, end, bounds) {
1593
+ const deltaLongitude = end[0] - start[0];
1594
+ const deltaLatitude = end[1] - start[1];
1595
+ const range = clipParameterRange([
1596
+ [-deltaLongitude, start[0] - bounds.minLongitude],
1597
+ [deltaLongitude, bounds.maxLongitude - start[0]],
1598
+ [-deltaLatitude, start[1] - bounds.minLatitude],
1599
+ [deltaLatitude, bounds.maxLatitude - start[1]]
1600
+ ]);
1601
+ if (!range) return;
1602
+ const positionAt = (ratio) => [start[0] + deltaLongitude * ratio, start[1] + deltaLatitude * ratio];
1603
+ return [positionAt(range.entering), positionAt(range.leaving)];
1588
1604
  }
1589
- function textCorners(text) {
1590
- const haloExpansion = (text.haloWidthMm ?? 0) / 2;
1591
- const left = (text.anchor === "start" ? 0 : text.anchor === "end" ? -text.widthMm : -text.widthMm / 2) - haloExpansion;
1592
- const top = -text.heightMm / 2 - haloExpansion;
1593
- const width = text.widthMm + 2 * haloExpansion;
1594
- const height = text.heightMm + 2 * haloExpansion;
1595
- return [
1596
- [left, top],
1597
- [left + width, top],
1598
- [left + width, top + height],
1599
- [left, top + height]
1600
- ].map(([x, y]) => pointInRotatedFrame(text.position, text.rotationDegrees, x, y));
1605
+ function clipLineToBounds(positions, bounds) {
1606
+ return positions.slice(1).flatMap((end, index) => {
1607
+ const clipped = clipSegmentToBounds(positions[index], end, bounds);
1608
+ return clipped ? [[...clipped]] : [];
1609
+ });
1601
1610
  }
1602
- function rectangleCorners(frame) {
1603
- const right = frame.xMm + frame.widthMm;
1604
- const bottom = frame.yMm + frame.heightMm;
1605
- return [
1611
+ function clipRingToBounds(positions, bounds) {
1612
+ const verticalIntersection = (longitude, start, end) => {
1613
+ const ratio = (longitude - start[0]) / (end[0] - start[0]);
1614
+ return [longitude, start[1] + (end[1] - start[1]) * ratio];
1615
+ };
1616
+ const horizontalIntersection = (latitude, start, end) => {
1617
+ const ratio = (latitude - start[1]) / (end[1] - start[1]);
1618
+ return [start[0] + (end[0] - start[0]) * ratio, latitude];
1619
+ };
1620
+ const boundaries = [
1606
1621
  {
1607
- xMm: frame.xMm,
1608
- yMm: frame.yMm
1622
+ inside: (position) => position[0] >= bounds.minLongitude,
1623
+ intersection: (start, end) => verticalIntersection(bounds.minLongitude, start, end)
1609
1624
  },
1610
1625
  {
1611
- xMm: right,
1612
- yMm: frame.yMm
1626
+ inside: (position) => position[0] <= bounds.maxLongitude,
1627
+ intersection: (start, end) => verticalIntersection(bounds.maxLongitude, start, end)
1613
1628
  },
1614
1629
  {
1615
- xMm: right,
1616
- yMm: bottom
1630
+ inside: (position) => position[1] >= bounds.minLatitude,
1631
+ intersection: (start, end) => horizontalIntersection(bounds.minLatitude, start, end)
1617
1632
  },
1618
1633
  {
1619
- xMm: frame.xMm,
1620
- yMm: bottom
1634
+ inside: (position) => position[1] <= bounds.maxLatitude,
1635
+ intersection: (start, end) => horizontalIntersection(bounds.maxLatitude, start, end)
1621
1636
  }
1622
1637
  ];
1638
+ const first = positions[0];
1639
+ const last = positions.at(-1);
1640
+ let clipped = first && last && first[0] === last[0] && first[1] === last[1] ? positions.slice(0, -1) : [...positions];
1641
+ for (const boundary of boundaries) {
1642
+ const input = clipped;
1643
+ clipped = [];
1644
+ let start = input.at(-1);
1645
+ for (const end of input) {
1646
+ if (!start) break;
1647
+ if (boundary.inside(end)) {
1648
+ if (!boundary.inside(start)) clipped.push(boundary.intersection(start, end));
1649
+ clipped.push(end);
1650
+ } else if (boundary.inside(start)) clipped.push(boundary.intersection(start, end));
1651
+ start = end;
1652
+ }
1653
+ }
1654
+ if (clipped.length > 0) clipped.push([...clipped[0]]);
1655
+ return clipped;
1623
1656
  }
1624
- function expandFrame(frame, deltaMm) {
1625
- if (deltaMm === 0) return frame;
1626
- return {
1627
- xMm: frame.xMm - deltaMm,
1628
- yMm: frame.yMm - deltaMm,
1629
- widthMm: frame.widthMm + 2 * deltaMm,
1630
- heightMm: frame.heightMm + 2 * deltaMm
1631
- };
1632
- }
1633
- function visibilityOfElement(element, frame) {
1634
- const points = element.kind === "path" ? element.points : element.kind === "text" ? textCorners(element) : element.kind === "vector-symbol" ? vectorSymbolCorners(element) : rectangleCorners(element.frame);
1635
- const inflation = element.kind === "path" ? element.strokeWidthMm / 2 : 0;
1636
- const innerFrame = expandFrame(frame, -inflation);
1637
- const outerFrame = expandFrame(frame, inflation);
1638
- const inside = points.every((point) => pointInside(point, innerFrame));
1639
- const segments = points.slice(1).map((point, index) => [points[index], point]);
1640
- if ((element.kind !== "path" || element.closed) && points.length > 1) segments.push([points.at(-1), points[0]]);
1641
- return {
1642
- intersects: points.some((point) => pointInside(point, outerFrame)) || segments.some(([start, end]) => segmentIntersectsFrame(start, end, outerFrame)),
1643
- inside
1644
- };
1645
- }
1646
- function vectorSymbolCorners(element) {
1647
- return [
1648
- [0, 0],
1649
- [element.width, 0],
1650
- [element.width, element.height],
1651
- [0, element.height]
1652
- ].map(([x, y]) => pointInRotatedFrame(element.position, element.rotationDegrees, (x - element.anchor.x) * element.scaleMmPerUnit, (y - element.anchor.y) * element.scaleMmPerUnit));
1653
- }
1654
- function visibilityWarning(layerId, graphicId, elements, frame) {
1655
- const visibility = elements.map((element) => visibilityOfElement(element, frame));
1656
- if (!visibility.some((item) => item.intersects)) return {
1657
- code: "graphic-outside-frame",
1658
- layerId,
1659
- graphicId
1660
- };
1661
- if (!visibility.every((item) => item.inside)) return {
1662
- code: "graphic-clipped",
1663
- layerId,
1664
- graphicId
1665
- };
1666
- }
1667
- function renderGraphic(layerId, authored, portrayal, context) {
1668
- const graphic = authored.graphic;
1669
- requireIdentifier(graphic.id, "Graphic id");
1670
- if (graphic.kind === "point-symbol" || graphic.kind === "custom-symbol") {
1671
- if (projectionRangeError([graphic.position], context) && !boundsOverlap(geographicBounds([graphic.position], context.footprintRing[0][0]), frameGeographicBounds(context))) return { warnings: [{
1672
- code: "graphic-outside-frame",
1673
- layerId,
1674
- graphicId: graphic.id
1675
- }] };
1676
- if (graphic.kind === "point-symbol" && !context.pointSymbols) throw new Error(`Cannot render Graphic "${graphic.id}": a point-symbol capability is required`);
1677
- const vector = graphic.kind === "point-symbol" ? context.pointSymbols.render(graphic) : graphic.vector;
1678
- const result = graphic.kind === "point-symbol" ? renderPointSymbolElements(graphic, vector, context) : {
1679
- elements: [renderVectorSymbol(graphic, vector, context)],
1680
- status: "ok"
1657
+ function clipGeometryToBounds(geometry, bounds) {
1658
+ if (geometry.type === "Point") return;
1659
+ if (geometry.type === "LineString") {
1660
+ const lines = clipLineToBounds(geometry.coordinates, bounds);
1661
+ if (lines.length === 0) return;
1662
+ return lines.length === 1 ? {
1663
+ type: "LineString",
1664
+ coordinates: lines[0]
1665
+ } : {
1666
+ type: "MultiLineString",
1667
+ coordinates: lines
1681
1668
  };
1682
- const warnings = [];
1683
- if (result.status !== "ok") warnings.push({
1684
- code: "point-symbol-offset-unsupported",
1685
- layerId,
1686
- graphicId: graphic.id
1687
- });
1688
- if (graphic.kind === "point-symbol" && vector.valid === false) warnings.push({
1689
- code: "point-symbol-fallback",
1690
- layerId,
1691
- graphicId: graphic.id
1692
- });
1693
- const visibility = visibilityWarning(layerId, graphic.id, result.elements, context.frame);
1694
- if (visibility) warnings.push(visibility);
1695
- return {
1696
- graphic: {
1697
- id: graphic.id,
1698
- elements: result.elements
1699
- },
1700
- warnings
1669
+ }
1670
+ if (geometry.type === "MultiLineString") {
1671
+ const lines = geometry.coordinates.flatMap((line) => clipLineToBounds(line, bounds));
1672
+ return lines.length === 0 ? void 0 : {
1673
+ type: "MultiLineString",
1674
+ coordinates: lines
1701
1675
  };
1702
1676
  }
1703
- const graphicsStyle = {
1704
- color: portrayal.symbolColor,
1705
- strokeWidth: portrayal.strokeWidthCssPixels,
1706
- strokeDash: [...portrayal.strokeDashCssPixels]
1707
- };
1708
- let rendered;
1709
- try {
1710
- rendered = renderControlMeasure(graphic, {
1711
- validationMode: "throw",
1712
- graphicsStyle,
1713
- highlightAppearance: portrayal.highlightAppearance,
1714
- context: {
1715
- groundMetersPerCssPixel: context.groundMetersPerCssPixel,
1716
- labelSizeBand: portrayal.labelSizeBand,
1717
- measureText: measureOpenSans
1718
- }
1719
- });
1720
- } catch (error) {
1721
- throw new Error(`Cannot render Graphic "${graphic.id}": ${String(error)}`, { cause: error });
1677
+ if (geometry.type === "Polygon") {
1678
+ const rings = geometry.coordinates.map((ring) => clipRingToBounds(ring, bounds)).filter((ring) => ring.length >= 4);
1679
+ return rings.length === 0 ? void 0 : {
1680
+ type: "Polygon",
1681
+ coordinates: rings
1682
+ };
1722
1683
  }
1723
- if (rendered.features.length === 0) throw new Error(`Cannot render Graphic "${graphic.id}": rendering produced no content`);
1724
- const featurePositions = rendered.features.map((feature) => geometryPositions(feature.geometry));
1725
- const featureOutOfRange = featurePositions.map((positions) => projectionRangeError(positions, context));
1726
- const renderedPositions = featurePositions.flat();
1727
- const frameBounds = frameGeographicBounds(context);
1728
- if (featureOutOfRange.some(Boolean) && !boundsOverlap(geographicBounds(renderedPositions, context.footprintRing[0][0]), frameBounds)) return { warnings: [{
1729
- code: "graphic-outside-frame",
1730
- layerId,
1731
- graphicId: graphic.id
1732
- }] };
1733
- const constructionMetersPerCssPixel = resolveConstructionMetersPerCssPixel(graphic.controlPoints, context.groundMetersPerCssPixel);
1734
- const featureElements = rendered.features.map((feature, index) => {
1684
+ return geometry;
1685
+ }
1686
+ function geometryPositions(geometry) {
1687
+ switch (geometry.type) {
1688
+ case "Point": return [geometry.coordinates];
1689
+ case "MultiPoint":
1690
+ case "LineString": return geometry.coordinates;
1691
+ case "MultiLineString":
1692
+ case "Polygon": return geometry.coordinates.flat();
1693
+ case "MultiPolygon": return geometry.coordinates.flat(2);
1694
+ case "GeometryCollection": return geometry.geometries.flatMap(geometryPositions);
1695
+ default: return assertNever(geometry);
1696
+ }
1697
+ }
1698
+ function projectionRangeError(positions, context) {
1699
+ return positions.some((position) => {
1735
1700
  try {
1736
- const geometry = featureOutOfRange[index] ? clipGeometryToBounds(feature.geometry, frameBounds) : feature.geometry;
1737
- return geometry ? elementsFromGeometry({
1738
- ...feature,
1739
- geometry
1740
- }, portrayal, context, constructionMetersPerCssPixel) : [];
1701
+ geographicLibGridProjection.forward(context.crs, position);
1702
+ return false;
1741
1703
  } catch (error) {
1742
- throw new Error(`Cannot render Graphic "${graphic.id}": ${String(error)}`, { cause: error });
1704
+ return isGridProjectionRangeError(error);
1743
1705
  }
1744
1706
  });
1745
- const elements = [...highlightBandsInPaintOrder(rendered.features, portrayal.strokeWidthCssPixels).flatMap(({ feature, band }) => highlightBandPaths(band, featureElements[rendered.features.indexOf(feature)])), ...featureElements.flat()];
1746
- if (elements.length === 0 && rendered.features.every((feature) => feature.properties.text !== void 0)) return { warnings: [{
1747
- code: "graphic-hidden",
1748
- layerId,
1749
- graphicId: graphic.id
1750
- }] };
1751
- if (elements.length === 0) throw new Error(`Cannot render Graphic "${graphic.id}": rendering produced no content`);
1707
+ }
1708
+ const frameBoundsCache = /* @__PURE__ */ new WeakMap();
1709
+ /** The footprint ring is fixed for a render pass, so its bounds are cached. */
1710
+ function frameGeographicBounds(context) {
1711
+ const cached = frameBoundsCache.get(context.footprintRing);
1712
+ if (cached) return cached;
1713
+ const longitudeReference = context.footprintRing[0][0];
1714
+ const bounds = geographicBounds(context.footprintRing, longitudeReference);
1715
+ frameBoundsCache.set(context.footprintRing, bounds);
1716
+ return bounds;
1717
+ }
1718
+ function positiveModulo(value, divisor) {
1719
+ return (value % divisor + divisor) % divisor;
1720
+ }
1721
+ function patternPaintToScene(paint, color) {
1752
1722
  return {
1753
- graphic: {
1754
- id: graphic.id,
1755
- elements
1756
- },
1757
- warnings: [visibilityWarning(layerId, graphic.id, elements, context.frame)].filter((warning) => warning !== void 0)
1723
+ ...paint.fill ? { fillColor: color } : {},
1724
+ ...paint.stroke ? { stroke: {
1725
+ color,
1726
+ widthMm: paint.stroke.width * MILLIMETRES_PER_CSS_PIXEL,
1727
+ lineCap: paint.stroke.lineCap,
1728
+ dashMm: (paint.stroke.dash ?? []).map((value) => value * MILLIMETRES_PER_CSS_PIXEL)
1729
+ } } : {}
1758
1730
  };
1759
1731
  }
1760
- function renderAuthoredLayers(authoredLayers, context) {
1761
- const warnings = [];
1762
- const patterns = [];
1763
- const renderContext = {
1764
- ...context,
1765
- patterns
1732
+ function patternCommandToScene(command, color) {
1733
+ const point = ([x, y]) => ({
1734
+ xMm: x * MILLIMETRES_PER_CSS_PIXEL,
1735
+ yMm: y * MILLIMETRES_PER_CSS_PIXEL
1736
+ });
1737
+ if (command.type === "circle") return {
1738
+ type: "circle",
1739
+ center: point(command.center),
1740
+ radiusMm: command.radius * MILLIMETRES_PER_CSS_PIXEL,
1741
+ paint: patternPaintToScene(command.paint, color)
1766
1742
  };
1767
- const fontStyles = /* @__PURE__ */ new Set();
1768
- const layerIds = /* @__PURE__ */ new Set();
1769
1743
  return {
1770
- layers: (authoredLayers ?? []).map((authoredLayer) => {
1771
- requireIdentifier(authoredLayer.id, "Layer id");
1772
- if (layerIds.has(authoredLayer.id)) throw new Error(`Duplicate layer id "${authoredLayer.id}"`);
1773
- layerIds.add(authoredLayer.id);
1774
- const portrayal = resolvePortrayal(authoredLayer.portrayal);
1775
- const graphicIds = /* @__PURE__ */ new Set();
1776
- const graphics = [];
1777
- for (const authored of authoredLayer.graphics) {
1778
- if (graphicIds.has(authored.graphic.id)) throw new Error(`Duplicate Graphic id "${authored.graphic.id}" in layer "${authoredLayer.id}"`);
1779
- graphicIds.add(authored.graphic.id);
1780
- const result = renderGraphic(authoredLayer.id, authored, portrayal, renderContext);
1781
- if (result.graphic) {
1782
- graphics.push(result.graphic);
1783
- for (const element of result.graphic.elements) if (element.kind === "text") fontStyles.add(element.fontStyle === "italic" ? "Italic" : element.fontWeight === 300 ? "Light" : "Regular");
1784
- else if (element.kind === "vector-symbol" && element.usesFont) fontStyles.add("Regular");
1785
- }
1786
- if (result.warnings) warnings.push(...result.warnings);
1787
- }
1744
+ type: "path",
1745
+ operations: command.operations.map((operation) => {
1746
+ if (operation.type === "close") return operation;
1747
+ if (operation.type === "cubic") return {
1748
+ type: "cubic",
1749
+ control1: point(operation.control1),
1750
+ control2: point(operation.control2),
1751
+ to: point(operation.to)
1752
+ };
1788
1753
  return {
1789
- id: authoredLayer.id,
1790
- graphics
1754
+ type: operation.type,
1755
+ to: point(operation.to)
1791
1756
  };
1792
1757
  }),
1793
- warnings,
1794
- fontStyles: [...fontStyles],
1795
- patterns
1758
+ paint: patternPaintToScene(command.paint, color)
1796
1759
  };
1797
1760
  }
1798
- function assertNever(value) {
1799
- throw new Error(`Unsupported geometry: ${String(value)}`);
1800
- }
1801
- //#endregion
1802
- //#region src/mgrs.ts
1803
- const mgrsBackend = GeographicLibMgrs.MGRS;
1804
- function invalidReference(reference, cause) {
1805
- const detail = cause instanceof Error ? cause.message : String(cause);
1806
- return /* @__PURE__ */ new RangeError(`Invalid MGRS reference ${JSON.stringify(reference)}: ${detail}`);
1761
+ function registerPattern(pattern, color, context) {
1762
+ const existing = context.patterns.find((resource) => resource.identity.pattern === pattern && resource.identity.color === color);
1763
+ if (existing) return existing.identity.id;
1764
+ const definition = getFillPatternDefinition(pattern);
1765
+ const tileWidthMm = definition.tile.width * MILLIMETRES_PER_CSS_PIXEL;
1766
+ const tileHeightMm = definition.tile.height * MILLIMETRES_PER_CSS_PIXEL;
1767
+ const patternFrame = {
1768
+ frame: context.frame,
1769
+ center: context.center,
1770
+ projectedMetresPerMillimetre: context.patternProjectedMetresPerMillimetre
1771
+ };
1772
+ const projectedOriginXMm = eastingToMillimetres(0, patternFrame);
1773
+ const projectedOriginYMm = northingToMillimetres(0, patternFrame);
1774
+ const resource = {
1775
+ identity: {
1776
+ id: `sheet-pattern-${context.patterns.length}`,
1777
+ pattern,
1778
+ color,
1779
+ tileWidthMm,
1780
+ tileHeightMm,
1781
+ phaseXMm: positiveModulo(projectedOriginXMm, tileWidthMm),
1782
+ phaseYMm: positiveModulo(projectedOriginYMm, tileHeightMm)
1783
+ },
1784
+ commands: definition.commands.map((command) => patternCommandToScene(command, color))
1785
+ };
1786
+ context.patterns.push(resource);
1787
+ return resource.identity.id;
1807
1788
  }
1808
- function compactReference(reference) {
1809
- if (typeof reference !== "string") throw invalidReference(String(reference), "expected a string");
1810
- const normalized = reference.replace(/\s/g, "").toUpperCase();
1811
- const match = /^(?:0[1-9]|[1-9]|[1-5][0-9]|60)[C-HJ-NP-X][A-HJ-NP-Z]{2}(\d*)$/.exec(normalized) ?? /^[ABYZ][A-HJ-NP-Z]{2}(\d*)$/.exec(normalized);
1812
- if (!match) throw invalidReference(reference, "expected a complete UTM or UPS grid reference");
1813
- if (match[1].length % 2 !== 0) throw invalidReference(reference, "easting and northing must have equal precision");
1814
- if (match[1].length > 10) throw invalidReference(reference, "precision cannot exceed 5 digits per axis");
1815
- return normalized;
1789
+ function requireIdentifier(value, name) {
1790
+ if (typeof value !== "string" || value.length === 0) throw new TypeError(`${name} is required`);
1816
1791
  }
1817
- function assertPrecision(precision) {
1818
- if (!Number.isInteger(precision) || precision < 0 || precision > 5) throw new RangeError("MGRS precision must be an integer from 0 through 5");
1792
+ function requireFiniteNonNegative(value, name) {
1793
+ if (!Number.isFinite(value) || value < 0) throw new RangeError(`${name} must be a finite non-negative number`);
1819
1794
  }
1820
- function pointForMgrsFormatting(coordinate, precision) {
1821
- if (coordinate.crs.kind !== "ups") return coordinate;
1822
- const cellSizeMeters = 1e5 / 10 ** precision;
1823
- if (coordinate.northing % cellSizeMeters !== 0) return coordinate;
1795
+ function resolvePortrayal(input) {
1796
+ const strokeWidthCssPixels = input?.strokeWidthCssPixels ?? DEFAULT_STROKE_WIDTH_CSS_PIXELS;
1797
+ requirePositiveFinite(strokeWidthCssPixels, "Stroke width");
1798
+ const strokeDashCssPixels = input?.strokeDashCssPixels ?? DEFAULT_STROKE_DASH_CSS_PIXELS;
1799
+ strokeDashCssPixels.forEach((value) => requireFiniteNonNegative(value, "Stroke dash"));
1800
+ const labelHeightCssPixels = input?.labelHeightCssPixels ?? DEFAULT_LABEL_HEIGHT_CSS_PIXELS;
1801
+ requirePositiveFinite(labelHeightCssPixels, "Label height");
1802
+ const labelSizeClampCssPixels = input?.labelSizeClampCssPixels ?? DEFAULT_LABEL_SIZE_BAND;
1803
+ requireFiniteNonNegative(labelSizeClampCssPixels.min, "Label clamp minimum");
1804
+ requireFiniteNonNegative(labelSizeClampCssPixels.max, "Label clamp maximum");
1805
+ const symbolColor = input?.symbolColor ?? DEFAULT_PORTRAYAL.symbolColor;
1806
+ if (typeof symbolColor !== "string" || symbolColor.length === 0) throw new TypeError("Symbol color is required");
1824
1807
  return {
1825
- easting: coordinate.easting,
1826
- northing: coordinate.northing + 1e-6
1808
+ symbolColor,
1809
+ strokeWidthCssPixels,
1810
+ strokeDashCssPixels,
1811
+ lineCap: input?.lineCap ?? DEFAULT_LINE_CAP,
1812
+ lineJoin: input?.lineJoin ?? DEFAULT_LINE_JOIN,
1813
+ labelHeightCssPixels,
1814
+ labelSizeClampCssPixels,
1815
+ labelSizeBand: {
1816
+ ...labelSizeClampCssPixels,
1817
+ belowMin: "pin"
1818
+ },
1819
+ highlightAppearance: input?.highlightAppearance
1827
1820
  };
1828
1821
  }
1829
- /** Parse a complete MGRS cell and resolve its southwest grid intersection. */
1830
- function parseMgrsReference(reference) {
1831
- const normalized = compactReference(reference);
1832
- try {
1833
- const result = mgrsBackend.reverse(normalized, false);
1834
- assertPrecision(result.prec);
1835
- const crs = result.zone === 0 ? {
1836
- kind: "ups",
1837
- hemisphere: result.northp ? "north" : "south"
1838
- } : {
1839
- kind: "utm",
1840
- zone: result.zone,
1841
- hemisphere: result.northp ? "north" : "south"
1842
- };
1843
- const position = geographicLibGridProjection.reverse(crs, {
1844
- easting: result.x,
1845
- northing: result.y
1846
- });
1847
- return {
1848
- normalized: projectedToMgrs({
1849
- crs,
1850
- easting: result.x,
1851
- northing: result.y
1852
- }, result.prec),
1853
- precision: result.prec,
1854
- crs,
1855
- easting: result.x,
1856
- northing: result.y,
1857
- position
1858
- };
1859
- } catch (error) {
1860
- if (error instanceof RangeError && error.message.startsWith("Invalid MGRS reference")) throw error;
1861
- throw invalidReference(reference, error);
1862
- }
1863
- }
1864
- function normalizeMgrsReference(reference) {
1865
- return parseMgrsReference(reference).normalized;
1822
+ function toScenePoint(position, context) {
1823
+ return projectedToScenePoint(geographicLibGridProjection.forward(context.crs, position), context);
1866
1824
  }
1867
- /** Convert an MGRS cell to its southwest intersection in its native grid CRS. */
1868
- function mgrsToProjected(reference) {
1869
- const { crs, easting, northing } = parseMgrsReference(reference);
1825
+ function pathFromPositions(positions, closed, properties, portrayal, context) {
1826
+ if (positions.length < 2) throw new Error("A document path requires at least two positions");
1827
+ const style = properties.style;
1828
+ const strokeWidthCssPixels = style?.strokeWidth ?? portrayal.strokeWidthCssPixels;
1829
+ requireFiniteNonNegative(strokeWidthCssPixels, "Stroke width");
1830
+ const strokeDashCssPixels = style?.strokeDash ?? portrayal.strokeDashCssPixels;
1831
+ strokeDashCssPixels.forEach((value) => requireFiniteNonNegative(value, "Stroke dash"));
1832
+ const fillPattern = style?.fillPattern;
1833
+ const fillColor = style?.fillColor;
1834
+ const fillPatternId = fillPattern && fillPattern !== "solid" && fillColor ? registerPattern(fillPattern, fillColor, context) : void 0;
1870
1835
  return {
1871
- crs,
1872
- easting,
1873
- northing
1836
+ kind: "path",
1837
+ points: positions.map((position) => toScenePoint(position, context)),
1838
+ ...closed ? { closed: true } : {},
1839
+ strokeColor: style?.strokeColor ?? portrayal.symbolColor,
1840
+ strokeWidthMm: strokeWidthCssPixels * MILLIMETRES_PER_CSS_PIXEL,
1841
+ strokeDashMm: strokeDashCssPixels.map((value) => value * MILLIMETRES_PER_CSS_PIXEL),
1842
+ lineCap: portrayal.lineCap,
1843
+ lineJoin: portrayal.lineJoin,
1844
+ ...fillColor ? { fillColor } : {},
1845
+ ...fillPatternId ? { fillPatternId } : {}
1874
1846
  };
1875
1847
  }
1876
- /** Convert an MGRS cell to its southwest intersection in GeoJSON coordinate order. */
1877
- function mgrsToGeographic(reference) {
1878
- return parseMgrsReference(reference).position;
1879
- }
1880
- function projectedToMgrs(coordinate, precision = 5) {
1881
- assertPrecision(precision);
1882
- return geographicLibGridProjection.formatMgrs(coordinate.crs, pointForMgrsFormatting(coordinate, precision), precision);
1883
- }
1884
- function geographicToMgrs(position, precision = 5) {
1885
- assertPrecision(precision);
1886
- const crs = geographicLibGridProjection.selectStandard(position);
1887
- return projectedToMgrs({
1888
- crs,
1889
- ...geographicLibGridProjection.forward(crs, position)
1890
- }, precision);
1891
- }
1892
- function snapUpOnHalf(value, interval) {
1893
- return Math.floor(value / interval + .5) * interval;
1894
- }
1895
- function snapProjectedToMgrs(coordinate, interval) {
1896
- const precision = mgrsPrecisionForInterval(interval);
1897
- const easting = snapUpOnHalf(coordinate.easting, interval);
1898
- const northing = snapUpOnHalf(coordinate.northing, interval);
1899
- return parseMgrsReference(projectedToMgrs({
1900
- crs: coordinate.crs,
1901
- easting,
1902
- northing
1903
- }, precision));
1904
- }
1905
- function snapGeographicToMgrs(position, interval) {
1906
- const crs = geographicLibGridProjection.selectStandard(position);
1907
- return snapProjectedToMgrs({
1908
- crs,
1909
- ...geographicLibGridProjection.forward(crs, position)
1910
- }, interval);
1911
- }
1912
- //#endregion
1913
- //#region src/registration.ts
1914
- const CROSSHAIR_HALF_SIZE_MM = 4;
1915
- const CROSSHAIR_STROKE_WIDTH_MM = DEFAULT_LINE_STROKE_WIDTH_MM;
1916
- const LABEL_GAP_MM = 1;
1917
- const LABEL_SIZE_CSS_PIXELS = 7;
1918
- function sameCrs(left, right) {
1919
- return left.kind === right.kind && left.hemisphere === right.hemisphere && (left.kind === "ups" || right.kind === "utm" && left.zone === right.zone);
1920
- }
1921
- function createCrosshairAxis(points, id, axis) {
1922
- return createSceneLine(points, "#000000", {
1923
- strokeWidthMm: CROSSHAIR_STROKE_WIDTH_MM,
1924
- attributes: {
1925
- "data-registration-id": id,
1926
- "data-registration-axis": axis,
1927
- "data-registration-size-mm": CROSSHAIR_HALF_SIZE_MM * 2
1928
- }
1929
- });
1848
+ function resolveTextSizeCssPixels(properties, portrayal, constructionMetersPerCssPixel) {
1849
+ if (properties.textSizePixels === void 0 && properties.textSizeMeters === void 0) return portrayal.labelHeightCssPixels;
1850
+ const { min, max } = portrayal.labelSizeClampCssPixels;
1851
+ const band = {
1852
+ textSizeMinPixels: Math.min(min, max),
1853
+ textSizeMaxPixels: Math.max(min, max)
1854
+ };
1855
+ return resolveTextAppearance({
1856
+ ...properties,
1857
+ ...band
1858
+ }, constructionMetersPerCssPixel, { pinBelowMinimum: true })?.sizePixels;
1930
1859
  }
1931
- function textBounds(text) {
1932
- const left = text.anchor === "start" ? text.position.xMm : text.anchor === "end" ? text.position.xMm - text.widthMm : text.position.xMm - text.widthMm / 2;
1860
+ /**
1861
+ * The scene point at `(x, y)` mm in a frame at `origin` rotated
1862
+ * `rotationDegrees` clockwise (scene y grows downward). Text, its screen-space
1863
+ * offset (`labelTextOffsetEms`, ADR-0068) and vector symbols all use it, so
1864
+ * they share one rotation convention.
1865
+ */
1866
+ function pointInRotatedFrame(origin, rotationDegrees, x, y) {
1867
+ const radians = rotationDegrees * Math.PI / 180;
1868
+ const cos = Math.cos(radians);
1869
+ const sin = Math.sin(radians);
1933
1870
  return {
1934
- left,
1935
- right: left + text.widthMm,
1936
- top: text.position.yMm - text.heightMm / 2,
1937
- bottom: text.position.yMm + text.heightMm / 2
1871
+ xMm: origin.xMm + x * cos - y * sin,
1872
+ yMm: origin.yMm + x * sin + y * cos
1938
1873
  };
1939
1874
  }
1940
- function contains(frame, bounds) {
1941
- return bounds.left >= frame.xMm && bounds.right <= frame.xMm + frame.widthMm && bounds.top >= frame.yMm && bounds.bottom <= frame.yMm + frame.heightMm;
1942
- }
1943
- function createCustomLabel(value, point, frame, id) {
1944
- const towardRight = point.xMm <= frame.xMm + frame.widthMm / 2;
1945
- return createRegularSceneText({
1946
- text: value,
1947
- xMm: point.xMm + (towardRight ? 1 : -1) * 5,
1948
- yMm: point.yMm,
1949
- sizeCssPixels: LABEL_SIZE_CSS_PIXELS,
1950
- color: "#000000",
1951
- anchor: towardRight ? "start" : "end",
1952
- attributes: {
1953
- "data-registration-id": id,
1954
- "data-registration-label": value
1955
- }
1875
+ function textFromFeature(feature, portrayal, context, constructionMetersPerCssPixel) {
1876
+ if (feature.geometry.type !== "Point" || feature.properties.text === void 0) return;
1877
+ const fontSizeCssPixels = resolveTextSizeCssPixels(feature.properties, portrayal, constructionMetersPerCssPixel);
1878
+ if (fontSizeCssPixels === void 0) return;
1879
+ requirePositiveFinite(fontSizeCssPixels, "Text size");
1880
+ const style = feature.properties.textStyle ?? "regular";
1881
+ const text = normalizeLogicalText(feature.properties.text, style);
1882
+ const measured = measureOpenSans({
1883
+ text,
1884
+ style,
1885
+ sizeCssPixels: fontSizeCssPixels
1956
1886
  });
1887
+ const fontSizeMm = fontSizeCssPixels * MILLIMETRES_PER_CSS_PIXEL;
1888
+ const rotationDegrees = (Math.PI - (feature.properties.rotation ?? Math.PI)) * 180 / Math.PI;
1889
+ const anchor = toScenePoint(feature.geometry.coordinates, context);
1890
+ const offsetEms = labelTextOffsetEms(feature.properties);
1891
+ return {
1892
+ kind: "text",
1893
+ position: offsetEms ? pointInRotatedFrame(anchor, rotationDegrees, offsetEms[0] * fontSizeMm, offsetEms[1] * fontSizeMm) : anchor,
1894
+ text,
1895
+ rotationDegrees,
1896
+ fontSizeMm,
1897
+ widthMm: measured.widthCssPixels * MILLIMETRES_PER_CSS_PIXEL,
1898
+ heightMm: measured.heightCssPixels * MILLIMETRES_PER_CSS_PIXEL,
1899
+ lineHeightMm: fontSizeMm * OPEN_SANS_LINE_HEIGHT_FACTOR,
1900
+ anchor: feature.properties.textAnchor === "start" ? "start" : feature.properties.textAnchor === "end" ? "end" : "middle",
1901
+ justify: feature.properties.textJustify ?? "center",
1902
+ color: feature.properties.style?.strokeColor ?? portrayal.symbolColor,
1903
+ background: feature.properties.textBackground === true,
1904
+ ...style === "italic" ? { fontStyle: "italic" } : {},
1905
+ ...style === "light" ? { fontWeight: 300 } : {},
1906
+ ...feature.properties.textHalo && feature.properties.textHaloColor ? {
1907
+ haloColor: feature.properties.textHaloColor,
1908
+ haloWidthMm: MILLIMETRES_PER_CSS_PIXEL
1909
+ } : {}
1910
+ };
1957
1911
  }
1958
- function splitGridCoordinates(reference) {
1959
- if (reference.precision === 0) return [reference.normalized.at(-2), reference.normalized.at(-1)];
1960
- const coordinates = reference.normalized.slice(-2 * reference.precision);
1961
- return [coordinates.slice(0, reference.precision), coordinates.slice(reference.precision)];
1912
+ /**
1913
+ * One Highlight band stroked along each path a highlighted line or area part
1914
+ * drew: the same geometry as one solid stroke in the resolved
1915
+ * `highlightColor`, never filled, so an area is cased along its outline only
1916
+ * and a transparent stroke is still cased. Glow bands carry their opacity, so
1917
+ * SVG and PDF print them alike.
1918
+ */
1919
+ function highlightBandPaths(band, parts) {
1920
+ return parts.flatMap((part) => part.kind === "path" ? [{
1921
+ kind: "path",
1922
+ points: part.points,
1923
+ ...part.closed ? { closed: true } : {},
1924
+ strokeColor: band.color,
1925
+ strokeWidthMm: band.width * MILLIMETRES_PER_CSS_PIXEL,
1926
+ ...band.opacity < 1 ? { strokeOpacity: band.opacity } : {},
1927
+ strokeDashMm: [],
1928
+ lineCap: "round",
1929
+ lineJoin: "round"
1930
+ }] : []);
1962
1931
  }
1963
- function createCoordinateLabels(reference, point, id) {
1964
- const [easting, northing] = splitGridCoordinates(reference);
1965
- return [createRegularSceneText({
1966
- text: northing,
1967
- xMm: point.xMm - CROSSHAIR_HALF_SIZE_MM - LABEL_GAP_MM,
1968
- yMm: point.yMm,
1969
- sizeCssPixels: LABEL_SIZE_CSS_PIXELS,
1970
- color: "#000000",
1971
- anchor: "end",
1972
- attributes: {
1973
- "data-registration-id": id,
1974
- "data-registration-label": northing,
1975
- "data-registration-coordinate": "northing"
1976
- }
1977
- }), createRegularSceneText({
1978
- text: easting,
1979
- xMm: point.xMm,
1980
- yMm: point.yMm + CROSSHAIR_HALF_SIZE_MM + LABEL_GAP_MM,
1981
- sizeCssPixels: LABEL_SIZE_CSS_PIXELS,
1982
- color: "#000000",
1983
- attributes: {
1984
- "data-registration-id": id,
1985
- "data-registration-label": easting,
1986
- "data-registration-coordinate": "easting"
1987
- }
1988
- })];
1932
+ function elementsFromGeometry(feature, portrayal, context, constructionMetersPerCssPixel) {
1933
+ const text = textFromFeature(feature, portrayal, context, constructionMetersPerCssPixel);
1934
+ if (text) return [text];
1935
+ if (feature.geometry.type === "Point" && feature.properties.text !== void 0) return [];
1936
+ const path = (positions, closed = false) => pathFromPositions(positions, closed, feature.properties, portrayal, context);
1937
+ switch (feature.geometry.type) {
1938
+ case "LineString": return [path(feature.geometry.coordinates)];
1939
+ case "MultiLineString": return feature.geometry.coordinates.map((line) => path(line));
1940
+ case "Polygon":
1941
+ if (feature.geometry.coordinates.length !== 1) throw new Error("Polygon holes are not representable in this milestone");
1942
+ return [path(feature.geometry.coordinates[0], true)];
1943
+ case "MultiPolygon":
1944
+ case "Point":
1945
+ case "MultiPoint": throw new Error(`${feature.geometry.type} features are not representable in this milestone`);
1946
+ case "GeometryCollection": throw new Error("GeometryCollection features cannot be represented by this document renderer");
1947
+ default: return assertNever(feature.geometry);
1948
+ }
1989
1949
  }
1990
- function assertMarkFits(point, labels, frame, id) {
1991
- const strokeEdge = 4.1;
1992
- if (!(point.xMm - strokeEdge >= frame.xMm && point.xMm + strokeEdge <= frame.xMm + frame.widthMm && point.yMm - strokeEdge >= frame.yMm && point.yMm + strokeEdge <= frame.yMm + frame.heightMm) || labels.some((label) => !contains(frame, textBounds(label)))) throw new RangeError(`Registration mark ${JSON.stringify(id)} and its label must fit within the printable map frame`);
1950
+ function pointInside(point, frame) {
1951
+ return point.xMm >= frame.xMm && point.xMm <= frame.xMm + frame.widthMm && point.yMm >= frame.yMm && point.yMm <= frame.yMm + frame.heightMm;
1993
1952
  }
1994
- function hasDistinctPair(marks) {
1995
- for (let left = 0; left < marks.length; left += 1) for (let right = left + 1; right < marks.length; right += 1) {
1996
- const first = marks[left].sheetPositionMm;
1997
- const second = marks[right].sheetPositionMm;
1998
- if (first.xMm !== second.xMm || first.yMm !== second.yMm) return true;
1999
- }
2000
- return false;
1953
+ function segmentIntersectsFrame(start, end, frame) {
1954
+ if (pointInside(start, frame) || pointInside(end, frame)) return true;
1955
+ const left = frame.xMm;
1956
+ const right = left + frame.widthMm;
1957
+ const top = frame.yMm;
1958
+ const bottom = top + frame.heightMm;
1959
+ const deltaX = end.xMm - start.xMm;
1960
+ const deltaY = end.yMm - start.yMm;
1961
+ return clipParameterRange([
1962
+ [-deltaX, start.xMm - left],
1963
+ [deltaX, right - start.xMm],
1964
+ [-deltaY, start.yMm - top],
1965
+ [deltaY, bottom - start.yMm]
1966
+ ]) !== void 0;
2001
1967
  }
2002
- function renderRegistration(request, context) {
2003
- if (!Array.isArray(request.marks) || request.marks.length < 2) throw new RangeError("Registration requires at least two authored marks");
2004
- const ids = /* @__PURE__ */ new Set();
2005
- const graphics = [];
2006
- const marks = [];
2007
- for (const authored of request.marks) {
2008
- if (typeof authored.id !== "string" || authored.id.trim() === "") throw new RangeError("Every registration mark requires a non-empty ID");
2009
- const idKey = authored.id.trim();
2010
- if (ids.has(idKey)) throw new RangeError(`Registration mark ID ${JSON.stringify(authored.id)} must be unique`);
2011
- ids.add(idKey);
2012
- const parsed = parseMgrsReference(authored.mgrs);
2013
- const resolved = request.snapIntervalMeters !== void 0 ? snapProjectedToMgrs(parsed, request.snapIntervalMeters) : parsed;
2014
- if (!sameCrs(resolved.crs, context.crs)) throw new RangeError(`Registration mark ${JSON.stringify(authored.id)} must use the sheet grid coordinate reference system`);
2015
- const sheetPositionMm = projectedToScenePoint(resolved, context);
2016
- const labels = authored.label && authored.label.trim() !== "" ? [createCustomLabel(authored.label, sheetPositionMm, context.frame, authored.id)] : createCoordinateLabels(resolved, sheetPositionMm, authored.id);
2017
- assertMarkFits(sheetPositionMm, labels, context.frame, authored.id);
2018
- marks.push({
2019
- id: authored.id,
2020
- mgrs: resolved.normalized,
2021
- position: [resolved.position[0], resolved.position[1]],
2022
- sheetPositionMm
2023
- });
2024
- const elements = [
2025
- createCrosshairAxis([{
2026
- xMm: sheetPositionMm.xMm - CROSSHAIR_HALF_SIZE_MM,
2027
- yMm: sheetPositionMm.yMm
2028
- }, {
2029
- xMm: sheetPositionMm.xMm + CROSSHAIR_HALF_SIZE_MM,
2030
- yMm: sheetPositionMm.yMm
2031
- }], authored.id, "horizontal"),
2032
- createCrosshairAxis([{
2033
- xMm: sheetPositionMm.xMm,
2034
- yMm: sheetPositionMm.yMm - CROSSHAIR_HALF_SIZE_MM
2035
- }, {
2036
- xMm: sheetPositionMm.xMm,
2037
- yMm: sheetPositionMm.yMm + CROSSHAIR_HALF_SIZE_MM
2038
- }], authored.id, "vertical"),
2039
- ...labels
2040
- ];
2041
- graphics.push({
2042
- id: authored.id,
2043
- elements
2044
- });
2045
- }
2046
- if (!hasDistinctPair(marks)) throw new RangeError("Registration requires marks at two distinct positions");
2047
- return {
2048
- layer: {
2049
- id: "registration-marks-0",
2050
- graphics,
2051
- attributes: { "data-registration-marks": marks.length }
2052
- },
2053
- marks
2054
- };
1968
+ function textCorners(text) {
1969
+ const haloExpansion = (text.haloWidthMm ?? 0) / 2;
1970
+ const left = (text.anchor === "start" ? 0 : text.anchor === "end" ? -text.widthMm : -text.widthMm / 2) - haloExpansion;
1971
+ const top = -text.heightMm / 2 - haloExpansion;
1972
+ const width = text.widthMm + 2 * haloExpansion;
1973
+ const height = text.heightMm + 2 * haloExpansion;
1974
+ return [
1975
+ [left, top],
1976
+ [left + width, top],
1977
+ [left + width, top + height],
1978
+ [left, top + height]
1979
+ ].map(([x, y]) => pointInRotatedFrame(text.position, text.rotationDegrees, x, y));
2055
1980
  }
2056
- //#endregion
2057
- //#region src/printer-calibration.ts
2058
- const DEFAULT_LENGTH_MM = 100;
2059
- const TICK_HALF_HEIGHT_MM = 2;
2060
- const LABEL_OFFSET_MM = 2.5;
2061
- const STROKE_WIDTH_MM = DEFAULT_LINE_STROKE_WIDTH_MM;
2062
- function line(points, attributes) {
2063
- return createSceneLine(points, "#000000", { attributes });
1981
+ function rectangleCorners(frame) {
1982
+ const right = frame.xMm + frame.widthMm;
1983
+ const bottom = frame.yMm + frame.heightMm;
1984
+ return [
1985
+ {
1986
+ xMm: frame.xMm,
1987
+ yMm: frame.yMm
1988
+ },
1989
+ {
1990
+ xMm: right,
1991
+ yMm: frame.yMm
1992
+ },
1993
+ {
1994
+ xMm: right,
1995
+ yMm: bottom
1996
+ },
1997
+ {
1998
+ xMm: frame.xMm,
1999
+ yMm: bottom
2000
+ }
2001
+ ];
2064
2002
  }
2065
- function renderPrinterCalibration(request, page, frame, reservedBottomMm = 0) {
2066
- const lengthMm = request.lengthMm ?? DEFAULT_LENGTH_MM;
2067
- requirePositiveFinite(lengthMm, "Printer-calibration length");
2068
- const centerX = page.widthMm / 2;
2069
- const frameBottom = frame.yMm + frame.heightMm;
2070
- const layoutBottom = page.heightMm - reservedBottomMm;
2071
- const yMm = frameBottom + (layoutBottom - frameBottom) / 2;
2072
- const startX = centerX - lengthMm / 2;
2073
- const endX = centerX + lengthMm / 2;
2074
- const label = createRegularSceneText({
2075
- text: `${lengthMm} mm`,
2076
- xMm: centerX,
2077
- yMm: yMm - LABEL_OFFSET_MM,
2078
- sizeCssPixels: 6,
2079
- color: "#000000",
2080
- attributes: { "data-printer-calibration-label": lengthMm }
2081
- });
2082
- const strokeEdge = STROKE_WIDTH_MM / 2;
2083
- const fitsHorizontally = startX - strokeEdge >= 0 && endX + strokeEdge <= page.widthMm;
2084
- const labelLeft = label.position.xMm - label.widthMm / 2;
2085
- const labelRight = label.position.xMm + label.widthMm / 2;
2086
- const contentTop = Math.min(label.position.yMm - label.heightMm / 2, yMm - TICK_HALF_HEIGHT_MM - strokeEdge);
2087
- const contentBottom = Math.max(label.position.yMm + label.heightMm / 2, yMm + TICK_HALF_HEIGHT_MM + strokeEdge);
2088
- if (!fitsHorizontally || labelLeft < 0 || labelRight > page.widthMm || contentTop < frameBottom || contentBottom > layoutBottom) throw new RangeError("The bottom page margin must fit the complete printer-calibration line, ticks, and label");
2003
+ function expandFrame(frame, deltaMm) {
2004
+ if (deltaMm === 0) return frame;
2089
2005
  return {
2090
- id: "printer-calibration-0",
2091
- graphics: [{
2092
- id: "printer-calibration",
2093
- elements: [
2094
- line([{
2095
- xMm: startX,
2096
- yMm
2097
- }, {
2098
- xMm: endX,
2099
- yMm
2100
- }], { "data-printer-calibration-length-mm": lengthMm }),
2101
- line([{
2102
- xMm: startX,
2103
- yMm: yMm - TICK_HALF_HEIGHT_MM
2104
- }, {
2105
- xMm: startX,
2106
- yMm: yMm + TICK_HALF_HEIGHT_MM
2107
- }], { "data-printer-calibration-tick": "start" }),
2108
- line([{
2109
- xMm: endX,
2110
- yMm: yMm - TICK_HALF_HEIGHT_MM
2111
- }, {
2112
- xMm: endX,
2113
- yMm: yMm + TICK_HALF_HEIGHT_MM
2114
- }], { "data-printer-calibration-tick": "end" }),
2115
- label
2116
- ]
2117
- }]
2006
+ xMm: frame.xMm - deltaMm,
2007
+ yMm: frame.yMm - deltaMm,
2008
+ widthMm: frame.widthMm + 2 * deltaMm,
2009
+ heightMm: frame.heightMm + 2 * deltaMm
2118
2010
  };
2119
2011
  }
2120
- //#endregion
2121
- //#region src/raster-plan.ts
2122
- function resolvePage(input) {
2123
- requirePositiveFinite(input.widthMm, "Page width");
2124
- requirePositiveFinite(input.heightMm, "Page height");
2125
- if (input.orientation === "landscape" && input.widthMm < input.heightMm || input.orientation === "portrait" && input.widthMm > input.heightMm) return {
2126
- widthMm: input.heightMm,
2127
- heightMm: input.widthMm
2128
- };
2012
+ function visibilityOfElement(element, frame) {
2013
+ const points = element.kind === "path" ? element.points : element.kind === "text" ? textCorners(element) : element.kind === "vector-symbol" ? vectorSymbolCorners(element) : rectangleCorners(element.frame);
2014
+ const inflation = element.kind === "path" ? element.strokeWidthMm / 2 : 0;
2015
+ const innerFrame = expandFrame(frame, -inflation);
2016
+ const outerFrame = expandFrame(frame, inflation);
2017
+ const inside = points.every((point) => pointInside(point, innerFrame));
2018
+ const segments = points.slice(1).map((point, index) => [points[index], point]);
2019
+ if ((element.kind !== "path" || element.closed) && points.length > 1) segments.push([points.at(-1), points[0]]);
2129
2020
  return {
2130
- widthMm: input.widthMm,
2131
- heightMm: input.heightMm
2021
+ intersects: points.some((point) => pointInside(point, outerFrame)) || segments.some(([start, end]) => segmentIntersectsFrame(start, end, outerFrame)),
2022
+ inside
2132
2023
  };
2133
2024
  }
2134
- function resolveFrame(request, page) {
2135
- if (request.mapFrame) {
2136
- if (request.page.marginMm !== void 0) throw new RangeError("Specify either a page margin or an explicit map frame, not both");
2137
- const { xMm, yMm, widthMm, heightMm } = request.mapFrame;
2138
- requirePositiveFinite(widthMm, "Map-frame width");
2139
- requirePositiveFinite(heightMm, "Map-frame height");
2140
- if (!Number.isFinite(xMm) || xMm < 0 || !Number.isFinite(yMm) || yMm < 0) throw new RangeError("Map-frame position must be finite and non-negative");
2141
- if (xMm + widthMm > page.widthMm || yMm + heightMm > page.heightMm) throw new RangeError("The map frame must fit within the physical page");
2142
- return {
2143
- xMm,
2144
- yMm,
2145
- widthMm,
2146
- heightMm
2147
- };
2025
+ function vectorSymbolCorners(element) {
2026
+ return [
2027
+ [0, 0],
2028
+ [element.width, 0],
2029
+ [element.width, element.height],
2030
+ [0, element.height]
2031
+ ].map(([x, y]) => pointInRotatedFrame(element.position, element.rotationDegrees, (x - element.anchor.x) * element.scaleMmPerUnit, (y - element.anchor.y) * element.scaleMmPerUnit));
2032
+ }
2033
+ function visibilityWarning(layerId, graphicId, elements, frame) {
2034
+ const visibility = elements.map((element) => visibilityOfElement(element, frame));
2035
+ if (!visibility.some((item) => item.intersects)) return {
2036
+ code: "graphic-outside-frame",
2037
+ layerId,
2038
+ graphicId
2039
+ };
2040
+ if (!visibility.every((item) => item.inside)) return {
2041
+ code: "graphic-clipped",
2042
+ layerId,
2043
+ graphicId
2044
+ };
2045
+ }
2046
+ function renderGraphic(layerId, authored, portrayal, context) {
2047
+ const graphic = authored.graphic;
2048
+ requireIdentifier(graphic.id, "Graphic id");
2049
+ if (graphic.kind === "point-symbol" || graphic.kind === "custom-symbol" || graphic.kind === "note") {
2050
+ if (projectionRangeError([graphic.position], context) && !boundsOverlap(geographicBounds([graphic.position], context.footprintRing[0][0]), frameGeographicBounds(context))) return { warnings: [{
2051
+ code: "graphic-outside-frame",
2052
+ layerId,
2053
+ graphicId: graphic.id
2054
+ }] };
2055
+ if (graphic.kind === "note") {
2056
+ if (!context.notes) throw new Error(`Cannot render Graphic "${graphic.id}": prepared note rasters are required (see prepareMapSheetNotes)`);
2057
+ let rendered;
2058
+ try {
2059
+ rendered = renderNoteElements(graphic, context.notes, context);
2060
+ } catch (error) {
2061
+ throw new Error(`Cannot render Graphic "${graphic.id}": ${String(error)}`, { cause: error });
2062
+ }
2063
+ const { elements } = rendered;
2064
+ const visibility = visibilityWarning(layerId, graphic.id, elements, context.frame);
2065
+ return {
2066
+ graphic: {
2067
+ id: graphic.id,
2068
+ elements
2069
+ },
2070
+ warnings: visibility ? [visibility] : []
2071
+ };
2072
+ }
2073
+ if (graphic.kind === "point-symbol" && !context.pointSymbols) throw new Error(`Cannot render Graphic "${graphic.id}": a point-symbol capability is required`);
2074
+ const vector = graphic.kind === "point-symbol" ? context.pointSymbols.render(graphic) : graphic.vector;
2075
+ const result = graphic.kind === "point-symbol" ? renderPointSymbolElements(graphic, vector, context) : {
2076
+ elements: [renderVectorSymbol(graphic, vector, context)],
2077
+ status: "ok"
2078
+ };
2079
+ const warnings = [];
2080
+ if (result.status !== "ok") warnings.push({
2081
+ code: "point-symbol-offset-unsupported",
2082
+ layerId,
2083
+ graphicId: graphic.id
2084
+ });
2085
+ if (graphic.kind === "point-symbol" && vector.valid === false) warnings.push({
2086
+ code: "point-symbol-fallback",
2087
+ layerId,
2088
+ graphicId: graphic.id
2089
+ });
2090
+ const visibility = visibilityWarning(layerId, graphic.id, result.elements, context.frame);
2091
+ if (visibility) warnings.push(visibility);
2092
+ return {
2093
+ graphic: {
2094
+ id: graphic.id,
2095
+ elements: result.elements
2096
+ },
2097
+ warnings
2098
+ };
2148
2099
  }
2149
- const marginMm = request.page.marginMm ?? 0;
2150
- if (!Number.isFinite(marginMm) || marginMm < 0) throw new RangeError("Page margin must be a finite non-negative number");
2151
- const widthMm = page.widthMm - 2 * marginMm;
2152
- const heightMm = page.heightMm - 2 * marginMm;
2153
- if (widthMm <= 0 || heightMm <= 0) throw new RangeError("Page margins must leave a positive map frame");
2100
+ const graphicsStyle = {
2101
+ color: portrayal.symbolColor,
2102
+ strokeWidth: portrayal.strokeWidthCssPixels,
2103
+ strokeDash: [...portrayal.strokeDashCssPixels]
2104
+ };
2105
+ let rendered;
2106
+ try {
2107
+ rendered = renderControlMeasure(graphic, {
2108
+ validationMode: "throw",
2109
+ graphicsStyle,
2110
+ highlightAppearance: portrayal.highlightAppearance,
2111
+ context: {
2112
+ groundMetersPerCssPixel: context.groundMetersPerCssPixel,
2113
+ labelSizeBand: portrayal.labelSizeBand,
2114
+ measureText: measureOpenSans
2115
+ }
2116
+ });
2117
+ } catch (error) {
2118
+ throw new Error(`Cannot render Graphic "${graphic.id}": ${String(error)}`, { cause: error });
2119
+ }
2120
+ if (rendered.features.length === 0) throw new Error(`Cannot render Graphic "${graphic.id}": rendering produced no content`);
2121
+ const featurePositions = rendered.features.map((feature) => geometryPositions(feature.geometry));
2122
+ const featureOutOfRange = featurePositions.map((positions) => projectionRangeError(positions, context));
2123
+ const renderedPositions = featurePositions.flat();
2124
+ const frameBounds = frameGeographicBounds(context);
2125
+ if (featureOutOfRange.some(Boolean) && !boundsOverlap(geographicBounds(renderedPositions, context.footprintRing[0][0]), frameBounds)) return { warnings: [{
2126
+ code: "graphic-outside-frame",
2127
+ layerId,
2128
+ graphicId: graphic.id
2129
+ }] };
2130
+ const constructionMetersPerCssPixel = resolveConstructionMetersPerCssPixel(graphic.controlPoints, context.groundMetersPerCssPixel);
2131
+ const featureElements = rendered.features.map((feature, index) => {
2132
+ try {
2133
+ const geometry = featureOutOfRange[index] ? clipGeometryToBounds(feature.geometry, frameBounds) : feature.geometry;
2134
+ return geometry ? elementsFromGeometry({
2135
+ ...feature,
2136
+ geometry
2137
+ }, portrayal, context, constructionMetersPerCssPixel) : [];
2138
+ } catch (error) {
2139
+ throw new Error(`Cannot render Graphic "${graphic.id}": ${String(error)}`, { cause: error });
2140
+ }
2141
+ });
2142
+ const elements = [...highlightBandsInPaintOrder(rendered.features, portrayal.strokeWidthCssPixels).flatMap(({ feature, band }) => highlightBandPaths(band, featureElements[rendered.features.indexOf(feature)])), ...featureElements.flat()];
2143
+ if (elements.length === 0 && rendered.features.every((feature) => feature.properties.text !== void 0)) return { warnings: [{
2144
+ code: "graphic-hidden",
2145
+ layerId,
2146
+ graphicId: graphic.id
2147
+ }] };
2148
+ if (elements.length === 0) throw new Error(`Cannot render Graphic "${graphic.id}": rendering produced no content`);
2154
2149
  return {
2155
- xMm: marginMm,
2156
- yMm: marginMm,
2157
- widthMm,
2158
- heightMm
2150
+ graphic: {
2151
+ id: graphic.id,
2152
+ elements
2153
+ },
2154
+ warnings: [visibilityWarning(layerId, graphic.id, elements, context.frame)].filter((warning) => warning !== void 0)
2159
2155
  };
2160
2156
  }
2161
- function resolveProjection(requested, center) {
2162
- const selected = geographicLibGridProjection.selectStandard(center);
2163
- if (requested === void 0 || requested === "auto") return selected;
2164
- if (requested.hemisphere !== selected.hemisphere) throw new RangeError("The explicit projection hemisphere must contain the sheet center");
2165
- if (requested.kind === "ups" && selected.kind !== "ups") throw new RangeError("UPS can only be selected for a center in a polar UPS region");
2166
- return requested;
2167
- }
2168
- function epsgFor(crs) {
2169
- if (crs.kind === "ups") return crs.hemisphere === "north" ? 32661 : 32761;
2170
- return (crs.hemisphere === "north" ? 32600 : 32700) + crs.zone;
2171
- }
2172
- function resolveMapSheetGeometry(request) {
2173
- requirePositiveFinite(request.scaleDenominator, "Scale denominator");
2174
- const page = resolvePage(request.page);
2175
- const frame = resolveFrame(request, page);
2176
- const crs = resolveProjection(request.projection, request.center);
2177
- const center = geographicLibGridProjection.forward(crs, request.center);
2178
- if (!(center.pointScale > 0)) throw new Error("Projection point scale must be positive");
2179
- const projectedMetresPerMillimetre = request.scaleDenominator / 1e3 * center.pointScale;
2180
- const projectedWidth = frame.widthMm * projectedMetresPerMillimetre;
2181
- const projectedHeight = frame.heightMm * projectedMetresPerMillimetre;
2157
+ function renderAuthoredLayers(authoredLayers, context) {
2158
+ const warnings = [];
2159
+ const patterns = [];
2160
+ const renderContext = {
2161
+ ...context,
2162
+ patterns
2163
+ };
2164
+ const fontStyles = /* @__PURE__ */ new Set();
2165
+ const layerIds = /* @__PURE__ */ new Set();
2182
2166
  return {
2183
- page,
2184
- center,
2185
- plan: {
2186
- crs,
2187
- epsg: epsgFor(crs),
2188
- frame,
2189
- projectedMetresPerMillimetre,
2190
- projectedBounds: {
2191
- left: center.easting - projectedWidth / 2,
2192
- bottom: center.northing - projectedHeight / 2,
2193
- right: center.easting + projectedWidth / 2,
2194
- top: center.northing + projectedHeight / 2
2167
+ layers: (authoredLayers ?? []).map((authoredLayer) => {
2168
+ requireIdentifier(authoredLayer.id, "Layer id");
2169
+ if (layerIds.has(authoredLayer.id)) throw new Error(`Duplicate layer id "${authoredLayer.id}"`);
2170
+ layerIds.add(authoredLayer.id);
2171
+ const portrayal = resolvePortrayal(authoredLayer.portrayal);
2172
+ const graphicIds = /* @__PURE__ */ new Set();
2173
+ const graphics = [];
2174
+ for (const authored of authoredLayer.graphics) {
2175
+ if (graphicIds.has(authored.graphic.id)) throw new Error(`Duplicate Graphic id "${authored.graphic.id}" in layer "${authoredLayer.id}"`);
2176
+ graphicIds.add(authored.graphic.id);
2177
+ const result = renderGraphic(authoredLayer.id, authored, portrayal, renderContext);
2178
+ if (result.graphic) {
2179
+ graphics.push(result.graphic);
2180
+ for (const element of result.graphic.elements) if (element.kind === "text") fontStyles.add(element.fontStyle === "italic" ? "Italic" : element.fontWeight === 300 ? "Light" : "Regular");
2181
+ else if (element.kind === "vector-symbol" && element.usesFont) fontStyles.add("Regular");
2182
+ }
2183
+ if (result.warnings) warnings.push(...result.warnings);
2195
2184
  }
2196
- }
2185
+ return {
2186
+ id: authoredLayer.id,
2187
+ graphics
2188
+ };
2189
+ }),
2190
+ warnings,
2191
+ fontStyles: [...fontStyles],
2192
+ patterns
2197
2193
  };
2198
2194
  }
2199
- function resolveMapSheetRasterPlan(request) {
2200
- return resolveMapSheetGeometry(request).plan;
2201
- }
2202
- function mapSheetRasterPointToGeographic(plan, normalizedX, normalizedY) {
2203
- if (!Number.isFinite(normalizedX) || normalizedX < 0 || normalizedX > 1 || !Number.isFinite(normalizedY) || normalizedY < 0 || normalizedY > 1) throw new RangeError("Normalized raster coordinates must be finite numbers from 0 through 1");
2204
- const bounds = plan.projectedBounds;
2205
- return geographicLibGridProjection.reverse(plan.crs, {
2206
- easting: bounds.left + normalizedX * (bounds.right - bounds.left),
2207
- northing: bounds.top - normalizedY * (bounds.top - bounds.bottom)
2208
- });
2195
+ function assertNever(value) {
2196
+ throw new Error(`Unsupported geometry: ${String(value)}`);
2209
2197
  }
2210
2198
  //#endregion
2211
- //#region src/raster-basemap.ts
2212
- const TESSELLATION_TOLERANCE_MM = 1e-6;
2213
- const LOW_DPI_THRESHOLD = 150;
2214
- const DPI_ANISOTROPY_THRESHOLD = .01;
2215
- function renderRasterBasemapLayers(basemap) {
2216
- return basemap.layers.map((layer) => ({
2217
- id: `raster-basemap-${layer.id}`,
2218
- attributes: {
2219
- "data-raster-layer": layer.id,
2220
- "data-opacity": layer.opacity
2221
- },
2222
- graphics: layer.tiles.map((tile) => ({
2223
- id: tile.id,
2224
- elements: [{
2225
- kind: "raster-image",
2226
- mediaType: tile.mediaType,
2227
- data: tile.data,
2228
- frame: { ...tile.frame },
2229
- opacity: layer.opacity,
2230
- resourceId: `${layer.id}/${tile.id}`
2231
- }]
2232
- }))
2233
- }));
2234
- }
2235
- function requireStableId(value, label, ids) {
2236
- if (typeof value !== "string" || value.trim() === "") throw new RangeError(`${label} must be a non-blank stable ID`);
2237
- if (ids.has(value)) throw new RangeError(`Duplicate ${label.toLowerCase()}: ${value}`);
2238
- ids.add(value);
2239
- }
2240
- function readUint32(bytes, offset, littleEndian = false) {
2241
- if (offset < 0 || offset + 4 > bytes.length) throw new RangeError("Malformed image data");
2242
- return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(offset, littleEndian);
2199
+ //#region src/mgrs.ts
2200
+ const mgrsBackend = GeographicLibMgrs.MGRS;
2201
+ function invalidReference(reference, cause) {
2202
+ const detail = cause instanceof Error ? cause.message : String(cause);
2203
+ return /* @__PURE__ */ new RangeError(`Invalid MGRS reference ${JSON.stringify(reference)}: ${detail}`);
2243
2204
  }
2244
- function readUint16(bytes, offset, littleEndian = false) {
2245
- if (offset < 0 || offset + 2 > bytes.length) throw new RangeError("Malformed image data");
2246
- return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint16(offset, littleEndian);
2205
+ function compactReference(reference) {
2206
+ if (typeof reference !== "string") throw invalidReference(String(reference), "expected a string");
2207
+ const normalized = reference.replace(/\s/g, "").toUpperCase();
2208
+ const match = /^(?:0[1-9]|[1-9]|[1-5][0-9]|60)[C-HJ-NP-X][A-HJ-NP-Z]{2}(\d*)$/.exec(normalized) ?? /^[ABYZ][A-HJ-NP-Z]{2}(\d*)$/.exec(normalized);
2209
+ if (!match) throw invalidReference(reference, "expected a complete UTM or UPS grid reference");
2210
+ if (match[1].length % 2 !== 0) throw invalidReference(reference, "easting and northing must have equal precision");
2211
+ if (match[1].length > 10) throw invalidReference(reference, "precision cannot exceed 5 digits per axis");
2212
+ return normalized;
2247
2213
  }
2248
- function ascii(bytes, offset, length) {
2249
- if (offset < 0 || offset + length > bytes.length) throw new RangeError("Malformed image data");
2250
- return String.fromCharCode(...bytes.subarray(offset, offset + length));
2214
+ function assertPrecision(precision) {
2215
+ if (!Number.isInteger(precision) || precision < 0 || precision > 5) throw new RangeError("MGRS precision must be an integer from 0 through 5");
2251
2216
  }
2252
- function inspectPng(bytes) {
2253
- if (bytes.length < 33 || [
2254
- 137,
2255
- 80,
2256
- 78,
2257
- 71,
2258
- 13,
2259
- 10,
2260
- 26,
2261
- 10
2262
- ].some((value, index) => bytes[index] !== value)) throw new RangeError("Malformed PNG image");
2263
- if (readUint32(bytes, 8) !== 13 || ascii(bytes, 12, 4) !== "IHDR") throw new RangeError("Malformed PNG image: IHDR must be first");
2264
- const width = readUint32(bytes, 16);
2265
- const height = readUint32(bytes, 20);
2266
- let offset = 8;
2267
- let ended = false;
2268
- while (offset + 12 <= bytes.length) {
2269
- const length = readUint32(bytes, offset);
2270
- const type = ascii(bytes, offset + 4, 4);
2271
- const next = offset + 12 + length;
2272
- if (next > bytes.length) throw new RangeError("Malformed PNG image chunk");
2273
- if (type === "acTL") throw new RangeError("APNG images are not supported");
2274
- offset = next;
2275
- if (type === "IEND") {
2276
- ended = true;
2277
- break;
2278
- }
2279
- }
2280
- if (!ended || offset !== bytes.length || width === 0 || height === 0) throw new RangeError("Malformed PNG image");
2217
+ function pointForMgrsFormatting(coordinate, precision) {
2218
+ if (coordinate.crs.kind !== "ups") return coordinate;
2219
+ const cellSizeMeters = 1e5 / 10 ** precision;
2220
+ if (coordinate.northing % cellSizeMeters !== 0) return coordinate;
2281
2221
  return {
2282
- width,
2283
- height
2222
+ easting: coordinate.easting,
2223
+ northing: coordinate.northing + 1e-6
2284
2224
  };
2285
2225
  }
2286
- function readExifOrientation(bytes, start, length) {
2287
- if (length < 6 || ascii(bytes, start, 6) !== "Exif\0\0") return void 0;
2288
- if (length < 14) throw new RangeError("Malformed JPEG EXIF data");
2289
- const tiff = start + 6;
2290
- const byteOrder = ascii(bytes, tiff, 2);
2291
- if (byteOrder !== "II" && byteOrder !== "MM") throw new RangeError("Malformed JPEG EXIF data");
2292
- const littleEndian = byteOrder === "II";
2293
- if (readUint16(bytes, tiff + 2, littleEndian) !== 42) throw new RangeError("Malformed JPEG EXIF data");
2294
- const ifd = tiff + readUint32(bytes, tiff + 4, littleEndian);
2295
- if (ifd + 2 > start + length) throw new RangeError("Malformed JPEG EXIF data");
2296
- const entries = readUint16(bytes, ifd, littleEndian);
2297
- for (let index = 0; index < entries; index += 1) {
2298
- const entry = ifd + 2 + index * 12;
2299
- if (entry + 12 > start + length) throw new RangeError("Malformed JPEG EXIF data");
2300
- if (readUint16(bytes, entry, littleEndian) === 274) {
2301
- if (readUint16(bytes, entry + 2, littleEndian) !== 3 || readUint32(bytes, entry + 4, littleEndian) !== 1) throw new RangeError("Malformed JPEG EXIF orientation");
2302
- return readUint16(bytes, entry + 8, littleEndian);
2303
- }
2226
+ /** Parse a complete MGRS cell and resolve its southwest grid intersection. */
2227
+ function parseMgrsReference(reference) {
2228
+ const normalized = compactReference(reference);
2229
+ try {
2230
+ const result = mgrsBackend.reverse(normalized, false);
2231
+ assertPrecision(result.prec);
2232
+ const crs = result.zone === 0 ? {
2233
+ kind: "ups",
2234
+ hemisphere: result.northp ? "north" : "south"
2235
+ } : {
2236
+ kind: "utm",
2237
+ zone: result.zone,
2238
+ hemisphere: result.northp ? "north" : "south"
2239
+ };
2240
+ const position = geographicLibGridProjection.reverse(crs, {
2241
+ easting: result.x,
2242
+ northing: result.y
2243
+ });
2244
+ return {
2245
+ normalized: projectedToMgrs({
2246
+ crs,
2247
+ easting: result.x,
2248
+ northing: result.y
2249
+ }, result.prec),
2250
+ precision: result.prec,
2251
+ crs,
2252
+ easting: result.x,
2253
+ northing: result.y,
2254
+ position
2255
+ };
2256
+ } catch (error) {
2257
+ if (error instanceof RangeError && error.message.startsWith("Invalid MGRS reference")) throw error;
2258
+ throw invalidReference(reference, error);
2304
2259
  }
2305
2260
  }
2306
- function inspectJpeg(bytes) {
2307
- if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216 || bytes.at(-2) !== 255 || bytes.at(-1) !== 217) throw new RangeError("Malformed JPEG image");
2308
- let offset = 2;
2309
- let dimensions;
2310
- let sawScan = false;
2311
- while (offset < bytes.length - 2) {
2312
- if (bytes[offset] !== 255) throw new RangeError("Malformed JPEG marker");
2313
- while (bytes[offset] === 255) offset += 1;
2314
- const marker = bytes[offset++];
2315
- if (marker === 217) break;
2316
- if (marker === 218) {
2317
- const segmentLength = readUint16(bytes, offset);
2318
- if (segmentLength < 2 || offset + segmentLength > bytes.length - 2) throw new RangeError("Malformed JPEG scan header");
2319
- sawScan = true;
2320
- break;
2321
- }
2322
- if (marker === 1 || marker >= 208 && marker <= 215) continue;
2323
- const segmentLength = readUint16(bytes, offset);
2324
- if (segmentLength < 2 || offset + segmentLength > bytes.length) throw new RangeError("Malformed JPEG segment");
2325
- const dataStart = offset + 2;
2326
- const dataLength = segmentLength - 2;
2327
- if (marker === 225) {
2328
- const orientation = readExifOrientation(bytes, dataStart, dataLength);
2329
- if (orientation !== void 0 && orientation !== 1) throw new RangeError(`JPEG EXIF orientation ${orientation} is not supported`);
2330
- }
2331
- if (marker === 192 || marker === 194) {
2332
- if (dataLength < 6) throw new RangeError("Malformed JPEG dimensions");
2333
- dimensions = {
2334
- height: readUint16(bytes, dataStart + 1),
2335
- width: readUint16(bytes, dataStart + 3)
2336
- };
2337
- } else if (marker >= 192 && marker <= 207 && ![
2338
- 196,
2339
- 200,
2340
- 204
2341
- ].includes(marker)) throw new RangeError("Only baseline and progressive JPEG images are supported");
2342
- offset += segmentLength;
2343
- }
2344
- if (!dimensions || dimensions.width === 0 || dimensions.height === 0 || !sawScan) throw new RangeError("Malformed JPEG image: dimensions are missing");
2345
- return dimensions;
2261
+ function normalizeMgrsReference(reference) {
2262
+ return parseMgrsReference(reference).normalized;
2346
2263
  }
2347
- function inspectImage(tile) {
2348
- if (!(tile.data instanceof Uint8Array) || tile.data.length === 0) throw new RangeError(`Raster tile ${tile.id} image bytes must be non-empty`);
2349
- if (!Number.isInteger(tile.pixelWidth) || tile.pixelWidth <= 0 || !Number.isInteger(tile.pixelHeight) || tile.pixelHeight <= 0) throw new RangeError(`Raster tile ${tile.id} pixel dimensions must be positive integers`);
2350
- const actual = tile.mediaType === "image/png" ? inspectPng(tile.data) : tile.mediaType === "image/jpeg" ? inspectJpeg(tile.data) : void 0;
2351
- if (!actual) throw new RangeError(`Raster tile ${tile.id} media type is not supported`);
2352
- if (actual.width !== tile.pixelWidth || actual.height !== tile.pixelHeight) {
2353
- const format = tile.mediaType === "image/png" ? "PNG" : "JPEG";
2354
- throw new RangeError(`Raster tile ${tile.id} declared dimensions ${tile.pixelWidth}x${tile.pixelHeight} do not match ${format} dimensions ${actual.width}x${actual.height}`);
2355
- }
2264
+ /** Convert an MGRS cell to its southwest intersection in its native grid CRS. */
2265
+ function mgrsToProjected(reference) {
2266
+ const { crs, easting, northing } = parseMgrsReference(reference);
2267
+ return {
2268
+ crs,
2269
+ easting,
2270
+ northing
2271
+ };
2356
2272
  }
2357
- function clustered(values) {
2358
- const sorted = [...values].sort((left, right) => left - right);
2359
- const result = [];
2360
- for (const value of sorted) if (result.length === 0 || value - result[result.length - 1] > TESSELLATION_TOLERANCE_MM) result.push(value);
2361
- return result;
2273
+ /** Convert an MGRS cell to its southwest intersection in GeoJSON coordinate order. */
2274
+ function mgrsToGeographic(reference) {
2275
+ return parseMgrsReference(reference).position;
2362
2276
  }
2363
- function validateTessellation(layer, frame) {
2364
- const right = frame.xMm + frame.widthMm;
2365
- const bottom = frame.yMm + frame.heightMm;
2366
- for (const tile of layer.tiles) {
2367
- const rectangle = tile.frame;
2368
- if (!Number.isFinite(rectangle.xMm) || !Number.isFinite(rectangle.yMm) || !Number.isFinite(rectangle.widthMm) || !Number.isFinite(rectangle.heightMm) || rectangle.widthMm <= 0 || rectangle.heightMm <= 0 || rectangle.xMm < frame.xMm - TESSELLATION_TOLERANCE_MM || rectangle.yMm < frame.yMm - TESSELLATION_TOLERANCE_MM || rectangle.xMm + rectangle.widthMm > right + TESSELLATION_TOLERANCE_MM || rectangle.yMm + rectangle.heightMm > bottom + TESSELLATION_TOLERANCE_MM) throw new RangeError(`Raster layer ${layer.id} must tessellate the complete map frame`);
2369
- }
2370
- const xs = clustered([
2371
- frame.xMm,
2372
- right,
2373
- ...layer.tiles.flatMap((tile) => [tile.frame.xMm, tile.frame.xMm + tile.frame.widthMm])
2374
- ]);
2375
- const ys = clustered([
2376
- frame.yMm,
2377
- bottom,
2378
- ...layer.tiles.flatMap((tile) => [tile.frame.yMm, tile.frame.yMm + tile.frame.heightMm])
2379
- ]);
2380
- for (let xIndex = 0; xIndex < xs.length - 1; xIndex += 1) for (let yIndex = 0; yIndex < ys.length - 1; yIndex += 1) {
2381
- const x = (xs[xIndex] + xs[xIndex + 1]) / 2;
2382
- const y = (ys[yIndex] + ys[yIndex + 1]) / 2;
2383
- if (x < frame.xMm || x > right || y < frame.yMm || y > bottom) continue;
2384
- if (layer.tiles.filter((tile) => x >= tile.frame.xMm - TESSELLATION_TOLERANCE_MM && x <= tile.frame.xMm + tile.frame.widthMm + TESSELLATION_TOLERANCE_MM && y >= tile.frame.yMm - TESSELLATION_TOLERANCE_MM && y <= tile.frame.yMm + tile.frame.heightMm + TESSELLATION_TOLERANCE_MM).length !== 1) throw new RangeError(`Raster layer ${layer.id} must tessellate the complete map frame`);
2385
- }
2277
+ function projectedToMgrs(coordinate, precision = 5) {
2278
+ assertPrecision(precision);
2279
+ return geographicLibGridProjection.formatMgrs(coordinate.crs, pointForMgrsFormatting(coordinate, precision), precision);
2386
2280
  }
2387
- function validateAttribution(attribution) {
2388
- return attribution.map((entry) => {
2389
- if (typeof entry.text !== "string" || entry.text.trim() === "") throw new RangeError("Raster attribution text must be non-blank");
2390
- if (typeof entry.required !== "boolean") throw new RangeError("Raster attribution requiredness must be explicit");
2391
- return {
2392
- text: entry.text,
2393
- required: entry.required
2394
- };
2395
- });
2281
+ function geographicToMgrs(position, precision = 5) {
2282
+ assertPrecision(precision);
2283
+ const crs = geographicLibGridProjection.selectStandard(position);
2284
+ return projectedToMgrs({
2285
+ crs,
2286
+ ...geographicLibGridProjection.forward(crs, position)
2287
+ }, precision);
2396
2288
  }
2397
- function resolveRasterBasemap(basemap, frame) {
2398
- if (basemap.layers.length === 0) throw new RangeError("A raster basemap requires at least one layer");
2399
- const layerIds = /* @__PURE__ */ new Set();
2400
- const tileIds = /* @__PURE__ */ new Set();
2401
- const attributionTexts = /* @__PURE__ */ new Set();
2402
- const warnings = [];
2403
- const allAttribution = [];
2404
- const layers = basemap.layers.map((layer) => {
2405
- requireStableId(layer.id, "Raster layer ID", layerIds);
2406
- if (!Number.isFinite(layer.opacity) || layer.opacity < 0 || layer.opacity > 1) throw new RangeError(`Raster layer ${layer.id} opacity must be from 0 through 1`);
2407
- if (layer.tiles.length === 0) throw new RangeError(`Raster layer ${layer.id} requires at least one tile`);
2408
- const attribution = validateAttribution(layer.attribution).filter((entry) => {
2409
- if (attributionTexts.has(entry.text)) return false;
2410
- attributionTexts.add(entry.text);
2411
- return true;
2412
- });
2413
- allAttribution.push(...attribution);
2414
- for (const tile of layer.tiles) {
2415
- requireStableId(tile.id, "Raster tile ID", tileIds);
2416
- inspectImage(tile);
2289
+ function snapUpOnHalf(value, interval) {
2290
+ return Math.floor(value / interval + .5) * interval;
2291
+ }
2292
+ function snapProjectedToMgrs(coordinate, interval) {
2293
+ const precision = mgrsPrecisionForInterval(interval);
2294
+ const easting = snapUpOnHalf(coordinate.easting, interval);
2295
+ const northing = snapUpOnHalf(coordinate.northing, interval);
2296
+ return parseMgrsReference(projectedToMgrs({
2297
+ crs: coordinate.crs,
2298
+ easting,
2299
+ northing
2300
+ }, precision));
2301
+ }
2302
+ function snapGeographicToMgrs(position, interval) {
2303
+ const crs = geographicLibGridProjection.selectStandard(position);
2304
+ return snapProjectedToMgrs({
2305
+ crs,
2306
+ ...geographicLibGridProjection.forward(crs, position)
2307
+ }, interval);
2308
+ }
2309
+ //#endregion
2310
+ //#region src/registration.ts
2311
+ const CROSSHAIR_HALF_SIZE_MM = 4;
2312
+ const CROSSHAIR_STROKE_WIDTH_MM = DEFAULT_LINE_STROKE_WIDTH_MM;
2313
+ const LABEL_GAP_MM = 1;
2314
+ const LABEL_SIZE_CSS_PIXELS = 7;
2315
+ function sameCrs(left, right) {
2316
+ return left.kind === right.kind && left.hemisphere === right.hemisphere && (left.kind === "ups" || right.kind === "utm" && left.zone === right.zone);
2317
+ }
2318
+ function createCrosshairAxis(points, id, axis) {
2319
+ return createSceneLine(points, "#000000", {
2320
+ strokeWidthMm: CROSSHAIR_STROKE_WIDTH_MM,
2321
+ attributes: {
2322
+ "data-registration-id": id,
2323
+ "data-registration-axis": axis,
2324
+ "data-registration-size-mm": CROSSHAIR_HALF_SIZE_MM * 2
2417
2325
  }
2418
- validateTessellation(layer, frame);
2419
- const tiles = layer.tiles.map((tile) => {
2420
- const effectiveHorizontalDpi = tile.pixelWidth * 25.4 / tile.frame.widthMm;
2421
- const effectiveVerticalDpi = tile.pixelHeight * 25.4 / tile.frame.heightMm;
2422
- if (effectiveHorizontalDpi < LOW_DPI_THRESHOLD || effectiveVerticalDpi < LOW_DPI_THRESHOLD) warnings.push({
2423
- code: "low-raster-dpi",
2424
- layerId: layer.id,
2425
- tileId: tile.id,
2426
- effectiveHorizontalDpi,
2427
- effectiveVerticalDpi,
2428
- thresholdDpi: LOW_DPI_THRESHOLD
2429
- });
2430
- const relativeDifference = Math.abs(effectiveHorizontalDpi - effectiveVerticalDpi) / Math.max(effectiveHorizontalDpi, effectiveVerticalDpi);
2431
- if (relativeDifference > DPI_ANISOTROPY_THRESHOLD) warnings.push({
2432
- code: "raster-dpi-anisotropy",
2433
- layerId: layer.id,
2434
- tileId: tile.id,
2435
- relativeDifference
2436
- });
2437
- return {
2438
- id: tile.id,
2439
- mediaType: tile.mediaType,
2440
- pixelWidth: tile.pixelWidth,
2441
- pixelHeight: tile.pixelHeight,
2442
- frame: { ...tile.frame },
2443
- effectiveHorizontalDpi,
2444
- effectiveVerticalDpi
2445
- };
2326
+ });
2327
+ }
2328
+ function textBounds(text) {
2329
+ const left = text.anchor === "start" ? text.position.xMm : text.anchor === "end" ? text.position.xMm - text.widthMm : text.position.xMm - text.widthMm / 2;
2330
+ return {
2331
+ left,
2332
+ right: left + text.widthMm,
2333
+ top: text.position.yMm - text.heightMm / 2,
2334
+ bottom: text.position.yMm + text.heightMm / 2
2335
+ };
2336
+ }
2337
+ function contains(frame, bounds) {
2338
+ return bounds.left >= frame.xMm && bounds.right <= frame.xMm + frame.widthMm && bounds.top >= frame.yMm && bounds.bottom <= frame.yMm + frame.heightMm;
2339
+ }
2340
+ function createCustomLabel(value, point, frame, id) {
2341
+ const towardRight = point.xMm <= frame.xMm + frame.widthMm / 2;
2342
+ return createRegularSceneText({
2343
+ text: value,
2344
+ xMm: point.xMm + (towardRight ? 1 : -1) * 5,
2345
+ yMm: point.yMm,
2346
+ sizeCssPixels: LABEL_SIZE_CSS_PIXELS,
2347
+ color: "#000000",
2348
+ anchor: towardRight ? "start" : "end",
2349
+ attributes: {
2350
+ "data-registration-id": id,
2351
+ "data-registration-label": value
2352
+ }
2353
+ });
2354
+ }
2355
+ function splitGridCoordinates(reference) {
2356
+ if (reference.precision === 0) return [reference.normalized.at(-2), reference.normalized.at(-1)];
2357
+ const coordinates = reference.normalized.slice(-2 * reference.precision);
2358
+ return [coordinates.slice(0, reference.precision), coordinates.slice(reference.precision)];
2359
+ }
2360
+ function createCoordinateLabels(reference, point, id) {
2361
+ const [easting, northing] = splitGridCoordinates(reference);
2362
+ return [createRegularSceneText({
2363
+ text: northing,
2364
+ xMm: point.xMm - CROSSHAIR_HALF_SIZE_MM - LABEL_GAP_MM,
2365
+ yMm: point.yMm,
2366
+ sizeCssPixels: LABEL_SIZE_CSS_PIXELS,
2367
+ color: "#000000",
2368
+ anchor: "end",
2369
+ attributes: {
2370
+ "data-registration-id": id,
2371
+ "data-registration-label": northing,
2372
+ "data-registration-coordinate": "northing"
2373
+ }
2374
+ }), createRegularSceneText({
2375
+ text: easting,
2376
+ xMm: point.xMm,
2377
+ yMm: point.yMm + CROSSHAIR_HALF_SIZE_MM + LABEL_GAP_MM,
2378
+ sizeCssPixels: LABEL_SIZE_CSS_PIXELS,
2379
+ color: "#000000",
2380
+ attributes: {
2381
+ "data-registration-id": id,
2382
+ "data-registration-label": easting,
2383
+ "data-registration-coordinate": "easting"
2384
+ }
2385
+ })];
2386
+ }
2387
+ function assertMarkFits(point, labels, frame, id) {
2388
+ const strokeEdge = 4.1;
2389
+ if (!(point.xMm - strokeEdge >= frame.xMm && point.xMm + strokeEdge <= frame.xMm + frame.widthMm && point.yMm - strokeEdge >= frame.yMm && point.yMm + strokeEdge <= frame.yMm + frame.heightMm) || labels.some((label) => !contains(frame, textBounds(label)))) throw new RangeError(`Registration mark ${JSON.stringify(id)} and its label must fit within the printable map frame`);
2390
+ }
2391
+ function hasDistinctPair(marks) {
2392
+ for (let left = 0; left < marks.length; left += 1) for (let right = left + 1; right < marks.length; right += 1) {
2393
+ const first = marks[left].sheetPositionMm;
2394
+ const second = marks[right].sheetPositionMm;
2395
+ if (first.xMm !== second.xMm || first.yMm !== second.yMm) return true;
2396
+ }
2397
+ return false;
2398
+ }
2399
+ function renderRegistration(request, context) {
2400
+ if (!Array.isArray(request.marks) || request.marks.length < 2) throw new RangeError("Registration requires at least two authored marks");
2401
+ const ids = /* @__PURE__ */ new Set();
2402
+ const graphics = [];
2403
+ const marks = [];
2404
+ for (const authored of request.marks) {
2405
+ if (typeof authored.id !== "string" || authored.id.trim() === "") throw new RangeError("Every registration mark requires a non-empty ID");
2406
+ const idKey = authored.id.trim();
2407
+ if (ids.has(idKey)) throw new RangeError(`Registration mark ID ${JSON.stringify(authored.id)} must be unique`);
2408
+ ids.add(idKey);
2409
+ const parsed = parseMgrsReference(authored.mgrs);
2410
+ const resolved = request.snapIntervalMeters !== void 0 ? snapProjectedToMgrs(parsed, request.snapIntervalMeters) : parsed;
2411
+ if (!sameCrs(resolved.crs, context.crs)) throw new RangeError(`Registration mark ${JSON.stringify(authored.id)} must use the sheet grid coordinate reference system`);
2412
+ const sheetPositionMm = projectedToScenePoint(resolved, context);
2413
+ const labels = authored.label && authored.label.trim() !== "" ? [createCustomLabel(authored.label, sheetPositionMm, context.frame, authored.id)] : createCoordinateLabels(resolved, sheetPositionMm, authored.id);
2414
+ assertMarkFits(sheetPositionMm, labels, context.frame, authored.id);
2415
+ marks.push({
2416
+ id: authored.id,
2417
+ mgrs: resolved.normalized,
2418
+ position: [resolved.position[0], resolved.position[1]],
2419
+ sheetPositionMm
2446
2420
  });
2421
+ const elements = [
2422
+ createCrosshairAxis([{
2423
+ xMm: sheetPositionMm.xMm - CROSSHAIR_HALF_SIZE_MM,
2424
+ yMm: sheetPositionMm.yMm
2425
+ }, {
2426
+ xMm: sheetPositionMm.xMm + CROSSHAIR_HALF_SIZE_MM,
2427
+ yMm: sheetPositionMm.yMm
2428
+ }], authored.id, "horizontal"),
2429
+ createCrosshairAxis([{
2430
+ xMm: sheetPositionMm.xMm,
2431
+ yMm: sheetPositionMm.yMm - CROSSHAIR_HALF_SIZE_MM
2432
+ }, {
2433
+ xMm: sheetPositionMm.xMm,
2434
+ yMm: sheetPositionMm.yMm + CROSSHAIR_HALF_SIZE_MM
2435
+ }], authored.id, "vertical"),
2436
+ ...labels
2437
+ ];
2438
+ graphics.push({
2439
+ id: authored.id,
2440
+ elements
2441
+ });
2442
+ }
2443
+ if (!hasDistinctPair(marks)) throw new RangeError("Registration requires marks at two distinct positions");
2444
+ return {
2445
+ layer: {
2446
+ id: "registration-marks-0",
2447
+ graphics,
2448
+ attributes: { "data-registration-marks": marks.length }
2449
+ },
2450
+ marks
2451
+ };
2452
+ }
2453
+ //#endregion
2454
+ //#region src/printer-calibration.ts
2455
+ const DEFAULT_LENGTH_MM = 100;
2456
+ const TICK_HALF_HEIGHT_MM = 2;
2457
+ const LABEL_OFFSET_MM = 2.5;
2458
+ const STROKE_WIDTH_MM = DEFAULT_LINE_STROKE_WIDTH_MM;
2459
+ function line(points, attributes) {
2460
+ return createSceneLine(points, "#000000", { attributes });
2461
+ }
2462
+ function renderPrinterCalibration(request, page, frame, reservedBottomMm = 0) {
2463
+ const lengthMm = request.lengthMm ?? DEFAULT_LENGTH_MM;
2464
+ requirePositiveFinite(lengthMm, "Printer-calibration length");
2465
+ const centerX = page.widthMm / 2;
2466
+ const frameBottom = frame.yMm + frame.heightMm;
2467
+ const layoutBottom = page.heightMm - reservedBottomMm;
2468
+ const yMm = frameBottom + (layoutBottom - frameBottom) / 2;
2469
+ const startX = centerX - lengthMm / 2;
2470
+ const endX = centerX + lengthMm / 2;
2471
+ const label = createRegularSceneText({
2472
+ text: `${lengthMm} mm`,
2473
+ xMm: centerX,
2474
+ yMm: yMm - LABEL_OFFSET_MM,
2475
+ sizeCssPixels: 6,
2476
+ color: "#000000",
2477
+ attributes: { "data-printer-calibration-label": lengthMm }
2478
+ });
2479
+ const strokeEdge = STROKE_WIDTH_MM / 2;
2480
+ const fitsHorizontally = startX - strokeEdge >= 0 && endX + strokeEdge <= page.widthMm;
2481
+ const labelLeft = label.position.xMm - label.widthMm / 2;
2482
+ const labelRight = label.position.xMm + label.widthMm / 2;
2483
+ const contentTop = Math.min(label.position.yMm - label.heightMm / 2, yMm - TICK_HALF_HEIGHT_MM - strokeEdge);
2484
+ const contentBottom = Math.max(label.position.yMm + label.heightMm / 2, yMm + TICK_HALF_HEIGHT_MM + strokeEdge);
2485
+ if (!fitsHorizontally || labelLeft < 0 || labelRight > page.widthMm || contentTop < frameBottom || contentBottom > layoutBottom) throw new RangeError("The bottom page margin must fit the complete printer-calibration line, ticks, and label");
2486
+ return {
2487
+ id: "printer-calibration-0",
2488
+ graphics: [{
2489
+ id: "printer-calibration",
2490
+ elements: [
2491
+ line([{
2492
+ xMm: startX,
2493
+ yMm
2494
+ }, {
2495
+ xMm: endX,
2496
+ yMm
2497
+ }], { "data-printer-calibration-length-mm": lengthMm }),
2498
+ line([{
2499
+ xMm: startX,
2500
+ yMm: yMm - TICK_HALF_HEIGHT_MM
2501
+ }, {
2502
+ xMm: startX,
2503
+ yMm: yMm + TICK_HALF_HEIGHT_MM
2504
+ }], { "data-printer-calibration-tick": "start" }),
2505
+ line([{
2506
+ xMm: endX,
2507
+ yMm: yMm - TICK_HALF_HEIGHT_MM
2508
+ }, {
2509
+ xMm: endX,
2510
+ yMm: yMm + TICK_HALF_HEIGHT_MM
2511
+ }], { "data-printer-calibration-tick": "end" }),
2512
+ label
2513
+ ]
2514
+ }]
2515
+ };
2516
+ }
2517
+ //#endregion
2518
+ //#region src/raster-plan.ts
2519
+ function resolvePage(input) {
2520
+ requirePositiveFinite(input.widthMm, "Page width");
2521
+ requirePositiveFinite(input.heightMm, "Page height");
2522
+ if (input.orientation === "landscape" && input.widthMm < input.heightMm || input.orientation === "portrait" && input.widthMm > input.heightMm) return {
2523
+ widthMm: input.heightMm,
2524
+ heightMm: input.widthMm
2525
+ };
2526
+ return {
2527
+ widthMm: input.widthMm,
2528
+ heightMm: input.heightMm
2529
+ };
2530
+ }
2531
+ function resolveFrame(request, page) {
2532
+ if (request.mapFrame) {
2533
+ if (request.page.marginMm !== void 0) throw new RangeError("Specify either a page margin or an explicit map frame, not both");
2534
+ const { xMm, yMm, widthMm, heightMm } = request.mapFrame;
2535
+ requirePositiveFinite(widthMm, "Map-frame width");
2536
+ requirePositiveFinite(heightMm, "Map-frame height");
2537
+ if (!Number.isFinite(xMm) || xMm < 0 || !Number.isFinite(yMm) || yMm < 0) throw new RangeError("Map-frame position must be finite and non-negative");
2538
+ if (xMm + widthMm > page.widthMm || yMm + heightMm > page.heightMm) throw new RangeError("The map frame must fit within the physical page");
2447
2539
  return {
2448
- resolved: {
2449
- id: layer.id,
2450
- opacity: layer.opacity,
2451
- tiles: [...layer.tiles]
2452
- },
2453
- metadata: {
2454
- id: layer.id,
2455
- opacity: layer.opacity,
2456
- attribution,
2457
- tiles
2458
- }
2540
+ xMm,
2541
+ yMm,
2542
+ widthMm,
2543
+ heightMm
2459
2544
  };
2460
- });
2545
+ }
2546
+ const marginMm = request.page.marginMm ?? 0;
2547
+ if (!Number.isFinite(marginMm) || marginMm < 0) throw new RangeError("Page margin must be a finite non-negative number");
2548
+ const widthMm = page.widthMm - 2 * marginMm;
2549
+ const heightMm = page.heightMm - 2 * marginMm;
2550
+ if (widthMm <= 0 || heightMm <= 0) throw new RangeError("Page margins must leave a positive map frame");
2461
2551
  return {
2462
- layers: layers.map((layer) => layer.resolved),
2463
- metadata: { layers: layers.map((layer) => layer.metadata) },
2464
- warnings,
2465
- attribution: allAttribution
2552
+ xMm: marginMm,
2553
+ yMm: marginMm,
2554
+ widthMm,
2555
+ heightMm
2466
2556
  };
2467
2557
  }
2558
+ function resolveProjection(requested, center) {
2559
+ const selected = geographicLibGridProjection.selectStandard(center);
2560
+ if (requested === void 0 || requested === "auto") return selected;
2561
+ if (requested.hemisphere !== selected.hemisphere) throw new RangeError("The explicit projection hemisphere must contain the sheet center");
2562
+ if (requested.kind === "ups" && selected.kind !== "ups") throw new RangeError("UPS can only be selected for a center in a polar UPS region");
2563
+ return requested;
2564
+ }
2565
+ function epsgFor(crs) {
2566
+ if (crs.kind === "ups") return crs.hemisphere === "north" ? 32661 : 32761;
2567
+ return (crs.hemisphere === "north" ? 32600 : 32700) + crs.zone;
2568
+ }
2569
+ function resolveMapSheetGeometry(request) {
2570
+ requirePositiveFinite(request.scaleDenominator, "Scale denominator");
2571
+ const page = resolvePage(request.page);
2572
+ const frame = resolveFrame(request, page);
2573
+ const crs = resolveProjection(request.projection, request.center);
2574
+ const center = geographicLibGridProjection.forward(crs, request.center);
2575
+ if (!(center.pointScale > 0)) throw new Error("Projection point scale must be positive");
2576
+ const projectedMetresPerMillimetre = request.scaleDenominator / 1e3 * center.pointScale;
2577
+ const projectedWidth = frame.widthMm * projectedMetresPerMillimetre;
2578
+ const projectedHeight = frame.heightMm * projectedMetresPerMillimetre;
2579
+ return {
2580
+ page,
2581
+ center,
2582
+ plan: {
2583
+ crs,
2584
+ epsg: epsgFor(crs),
2585
+ frame,
2586
+ projectedMetresPerMillimetre,
2587
+ projectedBounds: {
2588
+ left: center.easting - projectedWidth / 2,
2589
+ bottom: center.northing - projectedHeight / 2,
2590
+ right: center.easting + projectedWidth / 2,
2591
+ top: center.northing + projectedHeight / 2
2592
+ }
2593
+ }
2594
+ };
2595
+ }
2596
+ function resolveMapSheetRasterPlan(request) {
2597
+ return resolveMapSheetGeometry(request).plan;
2598
+ }
2599
+ function mapSheetRasterPointToGeographic(plan, normalizedX, normalizedY) {
2600
+ if (!Number.isFinite(normalizedX) || normalizedX < 0 || normalizedX > 1 || !Number.isFinite(normalizedY) || normalizedY < 0 || normalizedY > 1) throw new RangeError("Normalized raster coordinates must be finite numbers from 0 through 1");
2601
+ const bounds = plan.projectedBounds;
2602
+ return geographicLibGridProjection.reverse(plan.crs, {
2603
+ easting: bounds.left + normalizedX * (bounds.right - bounds.left),
2604
+ northing: bounds.top - normalizedY * (bounds.top - bounds.bottom)
2605
+ });
2606
+ }
2468
2607
  //#endregion
2469
2608
  //#region src/create-tactical-map-sheet.ts
2470
2609
  const FOOTPRINT_SEGMENTS_PER_EDGE = 16;
@@ -2572,7 +2711,8 @@ function createTacticalMapSheetDocument(request) {
2572
2711
  frame: mapFrame,
2573
2712
  footprintRing,
2574
2713
  groundMetersPerCssPixel: request.scaleDenominator * MILLIMETRES_PER_CSS_PIXEL / 1e3,
2575
- pointSymbols: request.pointSymbols
2714
+ pointSymbols: request.pointSymbols,
2715
+ notes: request.notes
2576
2716
  });
2577
2717
  const renderedGrid = request.grid && renderMgrsGrid(request.grid, {
2578
2718
  crs,
@@ -2657,4 +2797,4 @@ function createTacticalMapSheet(request) {
2657
2797
  return createTacticalMapSheetDocument(request).result;
2658
2798
  }
2659
2799
  //#endregion
2660
- export { openSansMiddleBaselineOffset as _, geographicToMgrs as a, normalizeMgrsReference as c, snapGeographicToMgrs as d, snapProjectedToMgrs as f, openSansCentralBaselineOffset as g, POINTS_PER_MILLIMETRE as h, resolveMapSheetRasterPlan as i, parseMgrsReference as l, MILLIMETRES_PER_CSS_PIXEL as m, createTacticalMapSheetDocument as n, mgrsToGeographic as o, formatDecimal as p, mapSheetRasterPointToGeographic as r, mgrsToProjected as s, createTacticalMapSheet as t, projectedToMgrs as u };
2800
+ export { openSansCentralBaselineOffset as _, geographicToMgrs as a, normalizeMgrsReference as c, snapGeographicToMgrs as d, snapProjectedToMgrs as f, POINTS_PER_MILLIMETRE as g, MILLIMETRES_PER_CSS_PIXEL as h, resolveMapSheetRasterPlan as i, parseMgrsReference as l, formatDecimal as m, createTacticalMapSheetDocument as n, mgrsToGeographic as o, prepareMapSheetNotes as p, mapSheetRasterPointToGeographic as r, mgrsToProjected as s, createTacticalMapSheet as t, projectedToMgrs as u, openSansMiddleBaselineOffset as v };