@orbat-mapper/tactical-map-sheet 0.6.9 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import GeographicLibMgrs from "geographiclib-mgrs";
2
2
  import PolarStereographic from "geographiclib-mgrs/src/polar-stereographic.mjs";
3
3
  import opentype from "opentype.js";
4
- import { DEFAULT_LABEL_HEIGHT_CSS_PIXELS, DEFAULT_LABEL_SIZE_BAND, DEFAULT_LINE_CAP, DEFAULT_LINE_JOIN, DEFAULT_PORTRAYAL, DEFAULT_STROKE_DASH_CSS_PIXELS, DEFAULT_STROKE_WIDTH_CSS_PIXELS, getFillPatternDefinition, renderControlMeasure, resolveConstructionMetersPerCssPixel, resolveSymbolColor } from "@orbat-mapper/control-measures";
4
+ import { DEFAULT_LABEL_HEIGHT_CSS_PIXELS, DEFAULT_LABEL_SIZE_BAND, DEFAULT_LINE_CAP, DEFAULT_LINE_JOIN, DEFAULT_PORTRAYAL, DEFAULT_STROKE_DASH_CSS_PIXELS, DEFAULT_STROKE_WIDTH_CSS_PIXELS, getFillPatternDefinition, labelTextOffsetEms, renderControlMeasure, resolveConstructionMetersPerCssPixel, resolveSymbolColor } from "@orbat-mapper/control-measures";
5
5
  import { effectivePointSymbolPixelSize, highlightBandsInPaintOrder, resolvePointSymbolOffset, resolveTextAppearance, scalePointSymbolLayout } from "@orbat-mapper/tactical-draw";
6
6
  import { SaxesParser } from "saxes";
7
7
  //#region src/projection/geographic-lib.ts
@@ -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,1296 +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;
1480
- }
1481
- function textFromFeature(feature, portrayal, context, constructionMetersPerCssPixel) {
1482
- if (feature.geometry.type !== "Point" || feature.properties.text === void 0) return;
1483
- const fontSizeCssPixels = resolveTextSizeCssPixels(feature.properties, portrayal, constructionMetersPerCssPixel);
1484
- if (fontSizeCssPixels === void 0) return;
1485
- requirePositiveFinite(fontSizeCssPixels, "Text size");
1486
- const style = feature.properties.textStyle ?? "regular";
1487
- const text = normalizeLogicalText(feature.properties.text, style);
1488
- const measured = measureOpenSans({
1489
- text,
1490
- style,
1491
- sizeCssPixels: fontSizeCssPixels
1492
- });
1493
- const fontSizeMm = fontSizeCssPixels * MILLIMETRES_PER_CSS_PIXEL;
1494
- return {
1495
- kind: "text",
1496
- position: toScenePoint(feature.geometry.coordinates, context),
1497
- text,
1498
- rotationDegrees: (Math.PI - (feature.properties.rotation ?? Math.PI)) * 180 / Math.PI,
1499
- fontSizeMm,
1500
- widthMm: measured.widthCssPixels * MILLIMETRES_PER_CSS_PIXEL,
1501
- heightMm: measured.heightCssPixels * MILLIMETRES_PER_CSS_PIXEL,
1502
- lineHeightMm: fontSizeMm * OPEN_SANS_LINE_HEIGHT_FACTOR,
1503
- anchor: feature.properties.textAnchor === "start" ? "start" : feature.properties.textAnchor === "end" ? "end" : "middle",
1504
- justify: feature.properties.textJustify ?? "center",
1505
- color: feature.properties.style?.strokeColor ?? portrayal.symbolColor,
1506
- background: feature.properties.textBackground === true,
1507
- ...style === "italic" ? { fontStyle: "italic" } : {},
1508
- ...style === "light" ? { fontWeight: 300 } : {},
1509
- ...feature.properties.textHalo && feature.properties.textHaloColor ? {
1510
- haloColor: feature.properties.textHaloColor,
1511
- haloWidthMm: MILLIMETRES_PER_CSS_PIXEL
1512
- } : {}
1513
- };
1566
+ function boundsOverlap(left, right) {
1567
+ return !(left.maxLongitude < right.minLongitude || left.minLongitude > right.maxLongitude || left.maxLatitude < right.minLatitude || left.minLatitude > right.maxLatitude);
1514
1568
  }
1515
1569
  /**
1516
- * One Highlight band stroked along each path a highlighted line or area part
1517
- * drew: the same geometry as one solid stroke in the resolved
1518
- * `highlightColor`, never filled, so an area is cased along its outline only
1519
- * and a transparent stroke is still cased. Glow bands carry their opacity, so
1520
- * SVG and PDF print them alike.
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.
1521
1573
  */
1522
- function highlightBandPaths(band, parts) {
1523
- return parts.flatMap((part) => part.kind === "path" ? [{
1524
- kind: "path",
1525
- points: part.points,
1526
- ...part.closed ? { closed: true } : {},
1527
- strokeColor: band.color,
1528
- strokeWidthMm: band.width * MILLIMETRES_PER_CSS_PIXEL,
1529
- ...band.opacity < 1 ? { strokeOpacity: band.opacity } : {},
1530
- strokeDashMm: [],
1531
- lineCap: "round",
1532
- lineJoin: "round"
1533
- }] : []);
1534
- }
1535
- function elementsFromGeometry(feature, portrayal, context, constructionMetersPerCssPixel) {
1536
- const text = textFromFeature(feature, portrayal, context, constructionMetersPerCssPixel);
1537
- if (text) return [text];
1538
- if (feature.geometry.type === "Point" && feature.properties.text !== void 0) return [];
1539
- const path = (positions, closed = false) => pathFromPositions(positions, closed, feature.properties, portrayal, context);
1540
- switch (feature.geometry.type) {
1541
- case "LineString": return [path(feature.geometry.coordinates)];
1542
- case "MultiLineString": return feature.geometry.coordinates.map((line) => path(line));
1543
- case "Polygon":
1544
- if (feature.geometry.coordinates.length !== 1) throw new Error("Polygon holes are not representable in this milestone");
1545
- return [path(feature.geometry.coordinates[0], true)];
1546
- case "MultiPolygon":
1547
- case "Point":
1548
- case "MultiPoint": throw new Error(`${feature.geometry.type} features are not representable in this milestone`);
1549
- case "GeometryCollection": throw new Error("GeometryCollection features cannot be represented by this document renderer");
1550
- default: return assertNever(feature.geometry);
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;
1551
1586
  }
1587
+ return {
1588
+ entering,
1589
+ leaving
1590
+ };
1552
1591
  }
1553
- function pointInside(point, frame) {
1554
- return point.xMm >= frame.xMm && point.xMm <= frame.xMm + frame.widthMm && point.yMm >= frame.yMm && point.yMm <= frame.yMm + frame.heightMm;
1555
- }
1556
- function segmentIntersectsFrame(start, end, frame) {
1557
- if (pointInside(start, frame) || pointInside(end, frame)) return true;
1558
- const left = frame.xMm;
1559
- const right = left + frame.widthMm;
1560
- const top = frame.yMm;
1561
- const bottom = top + frame.heightMm;
1562
- const deltaX = end.xMm - start.xMm;
1563
- const deltaY = end.yMm - start.yMm;
1564
- return clipParameterRange([
1565
- [-deltaX, start.xMm - left],
1566
- [deltaX, right - start.xMm],
1567
- [-deltaY, start.yMm - top],
1568
- [deltaY, bottom - start.yMm]
1569
- ]) !== 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)];
1570
1604
  }
1571
- function textCorners(text) {
1572
- const haloExpansion = (text.haloWidthMm ?? 0) / 2;
1573
- const left = (text.anchor === "start" ? 0 : text.anchor === "end" ? -text.widthMm : -text.widthMm / 2) - haloExpansion;
1574
- const top = -text.heightMm / 2 - haloExpansion;
1575
- const width = text.widthMm + 2 * haloExpansion;
1576
- const height = text.heightMm + 2 * haloExpansion;
1577
- const radians = text.rotationDegrees * Math.PI / 180;
1578
- const cos = Math.cos(radians);
1579
- const sin = Math.sin(radians);
1580
- return [
1581
- [left, top],
1582
- [left + width, top],
1583
- [left + width, top + height],
1584
- [left, top + height]
1585
- ].map(([x, y]) => ({
1586
- xMm: text.position.xMm + x * cos - y * sin,
1587
- yMm: text.position.yMm + x * sin + y * cos
1588
- }));
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
+ });
1589
1610
  }
1590
- function rectangleCorners(frame) {
1591
- const right = frame.xMm + frame.widthMm;
1592
- const bottom = frame.yMm + frame.heightMm;
1593
- 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 = [
1594
1621
  {
1595
- xMm: frame.xMm,
1596
- yMm: frame.yMm
1622
+ inside: (position) => position[0] >= bounds.minLongitude,
1623
+ intersection: (start, end) => verticalIntersection(bounds.minLongitude, start, end)
1597
1624
  },
1598
1625
  {
1599
- xMm: right,
1600
- yMm: frame.yMm
1626
+ inside: (position) => position[0] <= bounds.maxLongitude,
1627
+ intersection: (start, end) => verticalIntersection(bounds.maxLongitude, start, end)
1601
1628
  },
1602
1629
  {
1603
- xMm: right,
1604
- yMm: bottom
1630
+ inside: (position) => position[1] >= bounds.minLatitude,
1631
+ intersection: (start, end) => horizontalIntersection(bounds.minLatitude, start, end)
1605
1632
  },
1606
1633
  {
1607
- xMm: frame.xMm,
1608
- yMm: bottom
1634
+ inside: (position) => position[1] <= bounds.maxLatitude,
1635
+ intersection: (start, end) => horizontalIntersection(bounds.maxLatitude, start, end)
1609
1636
  }
1610
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;
1611
1656
  }
1612
- function expandFrame(frame, deltaMm) {
1613
- if (deltaMm === 0) return frame;
1614
- return {
1615
- xMm: frame.xMm - deltaMm,
1616
- yMm: frame.yMm - deltaMm,
1617
- widthMm: frame.widthMm + 2 * deltaMm,
1618
- heightMm: frame.heightMm + 2 * deltaMm
1619
- };
1620
- }
1621
- function visibilityOfElement(element, frame) {
1622
- const points = element.kind === "path" ? element.points : element.kind === "text" ? textCorners(element) : element.kind === "vector-symbol" ? vectorSymbolCorners(element) : rectangleCorners(element.frame);
1623
- const inflation = element.kind === "path" ? element.strokeWidthMm / 2 : 0;
1624
- const innerFrame = expandFrame(frame, -inflation);
1625
- const outerFrame = expandFrame(frame, inflation);
1626
- const inside = points.every((point) => pointInside(point, innerFrame));
1627
- const segments = points.slice(1).map((point, index) => [points[index], point]);
1628
- if ((element.kind !== "path" || element.closed) && points.length > 1) segments.push([points.at(-1), points[0]]);
1629
- return {
1630
- intersects: points.some((point) => pointInside(point, outerFrame)) || segments.some(([start, end]) => segmentIntersectsFrame(start, end, outerFrame)),
1631
- inside
1632
- };
1633
- }
1634
- function vectorSymbolCorners(element) {
1635
- const radians = element.rotationDegrees * Math.PI / 180;
1636
- const cos = Math.cos(radians);
1637
- const sin = Math.sin(radians);
1638
- return [
1639
- [0, 0],
1640
- [element.width, 0],
1641
- [element.width, element.height],
1642
- [0, element.height]
1643
- ].map(([x, y]) => {
1644
- const localX = (x - element.anchor.x) * element.scaleMmPerUnit;
1645
- const localY = (y - element.anchor.y) * element.scaleMmPerUnit;
1646
- return {
1647
- xMm: element.position.xMm + localX * cos - localY * sin,
1648
- yMm: element.position.yMm + localX * sin + localY * cos
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
1649
1668
  };
1650
- });
1651
- }
1652
- function visibilityWarning(layerId, graphicId, elements, frame) {
1653
- const visibility = elements.map((element) => visibilityOfElement(element, frame));
1654
- if (!visibility.some((item) => item.intersects)) return {
1655
- code: "graphic-outside-frame",
1656
- layerId,
1657
- graphicId
1658
- };
1659
- if (!visibility.every((item) => item.inside)) return {
1660
- code: "graphic-clipped",
1661
- layerId,
1662
- graphicId
1663
- };
1664
- }
1665
- function renderGraphic(layerId, authored, portrayal, context) {
1666
- const graphic = authored.graphic;
1667
- requireIdentifier(graphic.id, "Graphic id");
1668
- if (graphic.kind === "point-symbol" || graphic.kind === "custom-symbol") {
1669
- if (projectionRangeError([graphic.position], context) && !boundsOverlap(geographicBounds([graphic.position], context.footprintRing[0][0]), frameGeographicBounds(context))) return { warnings: [{
1670
- code: "graphic-outside-frame",
1671
- layerId,
1672
- graphicId: graphic.id
1673
- }] };
1674
- if (graphic.kind === "point-symbol" && !context.pointSymbols) throw new Error(`Cannot render Graphic "${graphic.id}": a point-symbol capability is required`);
1675
- const vector = graphic.kind === "point-symbol" ? context.pointSymbols.render(graphic) : graphic.vector;
1676
- const result = graphic.kind === "point-symbol" ? renderPointSymbolElements(graphic, vector, context) : {
1677
- elements: [renderVectorSymbol(graphic, vector, context)],
1678
- status: "ok"
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
1679
1675
  };
1680
- const warnings = [];
1681
- if (result.status !== "ok") warnings.push({
1682
- code: "point-symbol-offset-unsupported",
1683
- layerId,
1684
- graphicId: graphic.id
1685
- });
1686
- if (graphic.kind === "point-symbol" && vector.valid === false) warnings.push({
1687
- code: "point-symbol-fallback",
1688
- layerId,
1689
- graphicId: graphic.id
1690
- });
1691
- const visibility = visibilityWarning(layerId, graphic.id, result.elements, context.frame);
1692
- if (visibility) warnings.push(visibility);
1693
- return {
1694
- graphic: {
1695
- id: graphic.id,
1696
- elements: result.elements
1697
- },
1698
- warnings
1676
+ }
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
1699
1682
  };
1700
1683
  }
1701
- const graphicsStyle = {
1702
- color: portrayal.symbolColor,
1703
- strokeWidth: portrayal.strokeWidthCssPixels,
1704
- strokeDash: [...portrayal.strokeDashCssPixels]
1705
- };
1706
- let rendered;
1707
- try {
1708
- rendered = renderControlMeasure(graphic, {
1709
- validationMode: "throw",
1710
- graphicsStyle,
1711
- highlightAppearance: portrayal.highlightAppearance,
1712
- context: {
1713
- groundMetersPerCssPixel: context.groundMetersPerCssPixel,
1714
- labelSizeBand: portrayal.labelSizeBand,
1715
- measureText: measureOpenSans
1716
- }
1717
- });
1718
- } catch (error) {
1719
- throw new Error(`Cannot render Graphic "${graphic.id}": ${String(error)}`, { cause: error });
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);
1720
1696
  }
1721
- if (rendered.features.length === 0) throw new Error(`Cannot render Graphic "${graphic.id}": rendering produced no content`);
1722
- const featurePositions = rendered.features.map((feature) => geometryPositions(feature.geometry));
1723
- const featureOutOfRange = featurePositions.map((positions) => projectionRangeError(positions, context));
1724
- const renderedPositions = featurePositions.flat();
1725
- const frameBounds = frameGeographicBounds(context);
1726
- if (featureOutOfRange.some(Boolean) && !boundsOverlap(geographicBounds(renderedPositions, context.footprintRing[0][0]), frameBounds)) return { warnings: [{
1727
- code: "graphic-outside-frame",
1728
- layerId,
1729
- graphicId: graphic.id
1730
- }] };
1731
- const constructionMetersPerCssPixel = resolveConstructionMetersPerCssPixel(graphic.controlPoints, context.groundMetersPerCssPixel);
1732
- const featureElements = rendered.features.map((feature, index) => {
1697
+ }
1698
+ function projectionRangeError(positions, context) {
1699
+ return positions.some((position) => {
1733
1700
  try {
1734
- const geometry = featureOutOfRange[index] ? clipGeometryToBounds(feature.geometry, frameBounds) : feature.geometry;
1735
- return geometry ? elementsFromGeometry({
1736
- ...feature,
1737
- geometry
1738
- }, portrayal, context, constructionMetersPerCssPixel) : [];
1701
+ geographicLibGridProjection.forward(context.crs, position);
1702
+ return false;
1739
1703
  } catch (error) {
1740
- throw new Error(`Cannot render Graphic "${graphic.id}": ${String(error)}`, { cause: error });
1704
+ return isGridProjectionRangeError(error);
1741
1705
  }
1742
1706
  });
1743
- const elements = [...highlightBandsInPaintOrder(rendered.features, portrayal.strokeWidthCssPixels).flatMap(({ feature, band }) => highlightBandPaths(band, featureElements[rendered.features.indexOf(feature)])), ...featureElements.flat()];
1744
- if (elements.length === 0 && rendered.features.every((feature) => feature.properties.text !== void 0)) return { warnings: [{
1745
- code: "graphic-hidden",
1746
- layerId,
1747
- graphicId: graphic.id
1748
- }] };
1749
- 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) {
1750
1722
  return {
1751
- graphic: {
1752
- id: graphic.id,
1753
- elements
1754
- },
1755
- 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
+ } } : {}
1756
1730
  };
1757
1731
  }
1758
- function renderAuthoredLayers(authoredLayers, context) {
1759
- const warnings = [];
1760
- const patterns = [];
1761
- const renderContext = {
1762
- ...context,
1763
- 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)
1764
1742
  };
1765
- const fontStyles = /* @__PURE__ */ new Set();
1766
- const layerIds = /* @__PURE__ */ new Set();
1767
1743
  return {
1768
- layers: (authoredLayers ?? []).map((authoredLayer) => {
1769
- requireIdentifier(authoredLayer.id, "Layer id");
1770
- if (layerIds.has(authoredLayer.id)) throw new Error(`Duplicate layer id "${authoredLayer.id}"`);
1771
- layerIds.add(authoredLayer.id);
1772
- const portrayal = resolvePortrayal(authoredLayer.portrayal);
1773
- const graphicIds = /* @__PURE__ */ new Set();
1774
- const graphics = [];
1775
- for (const authored of authoredLayer.graphics) {
1776
- if (graphicIds.has(authored.graphic.id)) throw new Error(`Duplicate Graphic id "${authored.graphic.id}" in layer "${authoredLayer.id}"`);
1777
- graphicIds.add(authored.graphic.id);
1778
- const result = renderGraphic(authoredLayer.id, authored, portrayal, renderContext);
1779
- if (result.graphic) {
1780
- graphics.push(result.graphic);
1781
- for (const element of result.graphic.elements) if (element.kind === "text") fontStyles.add(element.fontStyle === "italic" ? "Italic" : element.fontWeight === 300 ? "Light" : "Regular");
1782
- else if (element.kind === "vector-symbol" && element.usesFont) fontStyles.add("Regular");
1783
- }
1784
- if (result.warnings) warnings.push(...result.warnings);
1785
- }
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
+ };
1786
1753
  return {
1787
- id: authoredLayer.id,
1788
- graphics
1754
+ type: operation.type,
1755
+ to: point(operation.to)
1789
1756
  };
1790
1757
  }),
1791
- warnings,
1792
- fontStyles: [...fontStyles],
1793
- patterns
1758
+ paint: patternPaintToScene(command.paint, color)
1794
1759
  };
1795
1760
  }
1796
- function assertNever(value) {
1797
- throw new Error(`Unsupported geometry: ${String(value)}`);
1798
- }
1799
- //#endregion
1800
- //#region src/mgrs.ts
1801
- const mgrsBackend = GeographicLibMgrs.MGRS;
1802
- function invalidReference(reference, cause) {
1803
- const detail = cause instanceof Error ? cause.message : String(cause);
1804
- return /* @__PURE__ */ new RangeError(`Invalid MGRS reference ${JSON.stringify(reference)}: ${detail}`);
1805
- }
1806
- function compactReference(reference) {
1807
- if (typeof reference !== "string") throw invalidReference(String(reference), "expected a string");
1808
- const normalized = reference.replace(/\s/g, "").toUpperCase();
1809
- 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);
1810
- if (!match) throw invalidReference(reference, "expected a complete UTM or UPS grid reference");
1811
- if (match[1].length % 2 !== 0) throw invalidReference(reference, "easting and northing must have equal precision");
1812
- if (match[1].length > 10) throw invalidReference(reference, "precision cannot exceed 5 digits per axis");
1813
- return normalized;
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;
1814
1788
  }
1815
- function assertPrecision(precision) {
1816
- if (!Number.isInteger(precision) || precision < 0 || precision > 5) throw new RangeError("MGRS precision must be an integer from 0 through 5");
1789
+ function requireIdentifier(value, name) {
1790
+ if (typeof value !== "string" || value.length === 0) throw new TypeError(`${name} is required`);
1817
1791
  }
1818
- function pointForMgrsFormatting(coordinate, precision) {
1819
- if (coordinate.crs.kind !== "ups") return coordinate;
1820
- const cellSizeMeters = 1e5 / 10 ** precision;
1821
- if (coordinate.northing % cellSizeMeters !== 0) return coordinate;
1822
- return {
1823
- easting: coordinate.easting,
1824
- northing: coordinate.northing + 1e-6
1825
- };
1792
+ function requireFiniteNonNegative(value, name) {
1793
+ if (!Number.isFinite(value) || value < 0) throw new RangeError(`${name} must be a finite non-negative number`);
1826
1794
  }
1827
- /** Parse a complete MGRS cell and resolve its southwest grid intersection. */
1828
- function parseMgrsReference(reference) {
1829
- const normalized = compactReference(reference);
1830
- try {
1831
- const result = mgrsBackend.reverse(normalized, false);
1832
- assertPrecision(result.prec);
1833
- const crs = result.zone === 0 ? {
1834
- kind: "ups",
1835
- hemisphere: result.northp ? "north" : "south"
1836
- } : {
1837
- kind: "utm",
1838
- zone: result.zone,
1839
- hemisphere: result.northp ? "north" : "south"
1840
- };
1841
- const position = geographicLibGridProjection.reverse(crs, {
1842
- easting: result.x,
1843
- northing: result.y
1844
- });
1845
- return {
1846
- normalized: projectedToMgrs({
1847
- crs,
1848
- easting: result.x,
1849
- northing: result.y
1850
- }, result.prec),
1851
- precision: result.prec,
1852
- crs,
1853
- easting: result.x,
1854
- northing: result.y,
1855
- position
1856
- };
1857
- } catch (error) {
1858
- if (error instanceof RangeError && error.message.startsWith("Invalid MGRS reference")) throw error;
1859
- throw invalidReference(reference, error);
1860
- }
1861
- }
1862
- function normalizeMgrsReference(reference) {
1863
- return parseMgrsReference(reference).normalized;
1864
- }
1865
- /** Convert an MGRS cell to its southwest intersection in its native grid CRS. */
1866
- function mgrsToProjected(reference) {
1867
- const { crs, easting, northing } = parseMgrsReference(reference);
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");
1868
1807
  return {
1869
- crs,
1870
- easting,
1871
- northing
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
1872
1820
  };
1873
1821
  }
1874
- /** Convert an MGRS cell to its southwest intersection in GeoJSON coordinate order. */
1875
- function mgrsToGeographic(reference) {
1876
- return parseMgrsReference(reference).position;
1877
- }
1878
- function projectedToMgrs(coordinate, precision = 5) {
1879
- assertPrecision(precision);
1880
- return geographicLibGridProjection.formatMgrs(coordinate.crs, pointForMgrsFormatting(coordinate, precision), precision);
1881
- }
1882
- function geographicToMgrs(position, precision = 5) {
1883
- assertPrecision(precision);
1884
- const crs = geographicLibGridProjection.selectStandard(position);
1885
- return projectedToMgrs({
1886
- crs,
1887
- ...geographicLibGridProjection.forward(crs, position)
1888
- }, precision);
1889
- }
1890
- function snapUpOnHalf(value, interval) {
1891
- return Math.floor(value / interval + .5) * interval;
1822
+ function toScenePoint(position, context) {
1823
+ return projectedToScenePoint(geographicLibGridProjection.forward(context.crs, position), context);
1892
1824
  }
1893
- function snapProjectedToMgrs(coordinate, interval) {
1894
- const precision = mgrsPrecisionForInterval(interval);
1895
- const easting = snapUpOnHalf(coordinate.easting, interval);
1896
- const northing = snapUpOnHalf(coordinate.northing, interval);
1897
- return parseMgrsReference(projectedToMgrs({
1898
- crs: coordinate.crs,
1899
- easting,
1900
- northing
1901
- }, precision));
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;
1835
+ return {
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 } : {}
1846
+ };
1902
1847
  }
1903
- function snapGeographicToMgrs(position, interval) {
1904
- const crs = geographicLibGridProjection.selectStandard(position);
1905
- return snapProjectedToMgrs({
1906
- crs,
1907
- ...geographicLibGridProjection.forward(crs, position)
1908
- }, interval);
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;
1909
1859
  }
1910
- //#endregion
1911
- //#region src/registration.ts
1912
- const CROSSHAIR_HALF_SIZE_MM = 4;
1913
- const CROSSHAIR_STROKE_WIDTH_MM = DEFAULT_LINE_STROKE_WIDTH_MM;
1914
- const LABEL_GAP_MM = 1;
1915
- const LABEL_SIZE_CSS_PIXELS = 7;
1916
- function sameCrs(left, right) {
1917
- return left.kind === right.kind && left.hemisphere === right.hemisphere && (left.kind === "ups" || right.kind === "utm" && left.zone === right.zone);
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);
1870
+ return {
1871
+ xMm: origin.xMm + x * cos - y * sin,
1872
+ yMm: origin.yMm + x * sin + y * cos
1873
+ };
1918
1874
  }
1919
- function createCrosshairAxis(points, id, axis) {
1920
- return createSceneLine(points, "#000000", {
1921
- strokeWidthMm: CROSSHAIR_STROKE_WIDTH_MM,
1922
- attributes: {
1923
- "data-registration-id": id,
1924
- "data-registration-axis": axis,
1925
- "data-registration-size-mm": CROSSHAIR_HALF_SIZE_MM * 2
1926
- }
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
1927
1886
  });
1928
- }
1929
- function textBounds(text) {
1930
- const left = text.anchor === "start" ? text.position.xMm : text.anchor === "end" ? text.position.xMm - text.widthMm : text.position.xMm - text.widthMm / 2;
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);
1931
1891
  return {
1932
- left,
1933
- right: left + text.widthMm,
1934
- top: text.position.yMm - text.heightMm / 2,
1935
- bottom: text.position.yMm + text.heightMm / 2
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
+ } : {}
1936
1910
  };
1937
1911
  }
1938
- function contains(frame, bounds) {
1939
- return bounds.left >= frame.xMm && bounds.right <= frame.xMm + frame.widthMm && bounds.top >= frame.yMm && bounds.bottom <= frame.yMm + frame.heightMm;
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
+ }] : []);
1940
1931
  }
1941
- function createCustomLabel(value, point, frame, id) {
1942
- const towardRight = point.xMm <= frame.xMm + frame.widthMm / 2;
1943
- return createRegularSceneText({
1944
- text: value,
1945
- xMm: point.xMm + (towardRight ? 1 : -1) * 5,
1946
- yMm: point.yMm,
1947
- sizeCssPixels: LABEL_SIZE_CSS_PIXELS,
1948
- color: "#000000",
1949
- anchor: towardRight ? "start" : "end",
1950
- attributes: {
1951
- "data-registration-id": id,
1952
- "data-registration-label": value
1953
- }
1954
- });
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
+ }
1955
1949
  }
1956
- function splitGridCoordinates(reference) {
1957
- if (reference.precision === 0) return [reference.normalized.at(-2), reference.normalized.at(-1)];
1958
- const coordinates = reference.normalized.slice(-2 * reference.precision);
1959
- return [coordinates.slice(0, reference.precision), coordinates.slice(reference.precision)];
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;
1960
1952
  }
1961
- function createCoordinateLabels(reference, point, id) {
1962
- const [easting, northing] = splitGridCoordinates(reference);
1963
- return [createRegularSceneText({
1964
- text: northing,
1965
- xMm: point.xMm - CROSSHAIR_HALF_SIZE_MM - LABEL_GAP_MM,
1966
- yMm: point.yMm,
1967
- sizeCssPixels: LABEL_SIZE_CSS_PIXELS,
1968
- color: "#000000",
1969
- anchor: "end",
1970
- attributes: {
1971
- "data-registration-id": id,
1972
- "data-registration-label": northing,
1973
- "data-registration-coordinate": "northing"
1974
- }
1975
- }), createRegularSceneText({
1976
- text: easting,
1977
- xMm: point.xMm,
1978
- yMm: point.yMm + CROSSHAIR_HALF_SIZE_MM + LABEL_GAP_MM,
1979
- sizeCssPixels: LABEL_SIZE_CSS_PIXELS,
1980
- color: "#000000",
1981
- attributes: {
1982
- "data-registration-id": id,
1983
- "data-registration-label": easting,
1984
- "data-registration-coordinate": "easting"
1985
- }
1986
- })];
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;
1987
1967
  }
1988
- function assertMarkFits(point, labels, frame, id) {
1989
- const strokeEdge = 4.1;
1990
- 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`);
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));
1991
1980
  }
1992
- function hasDistinctPair(marks) {
1993
- for (let left = 0; left < marks.length; left += 1) for (let right = left + 1; right < marks.length; right += 1) {
1994
- const first = marks[left].sheetPositionMm;
1995
- const second = marks[right].sheetPositionMm;
1996
- if (first.xMm !== second.xMm || first.yMm !== second.yMm) return true;
1997
- }
1998
- return false;
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
+ ];
1999
2002
  }
2000
- function renderRegistration(request, context) {
2001
- if (!Array.isArray(request.marks) || request.marks.length < 2) throw new RangeError("Registration requires at least two authored marks");
2002
- const ids = /* @__PURE__ */ new Set();
2003
- const graphics = [];
2004
- const marks = [];
2005
- for (const authored of request.marks) {
2006
- if (typeof authored.id !== "string" || authored.id.trim() === "") throw new RangeError("Every registration mark requires a non-empty ID");
2007
- const idKey = authored.id.trim();
2008
- if (ids.has(idKey)) throw new RangeError(`Registration mark ID ${JSON.stringify(authored.id)} must be unique`);
2009
- ids.add(idKey);
2010
- const parsed = parseMgrsReference(authored.mgrs);
2011
- const resolved = request.snapIntervalMeters !== void 0 ? snapProjectedToMgrs(parsed, request.snapIntervalMeters) : parsed;
2012
- if (!sameCrs(resolved.crs, context.crs)) throw new RangeError(`Registration mark ${JSON.stringify(authored.id)} must use the sheet grid coordinate reference system`);
2013
- const sheetPositionMm = projectedToScenePoint(resolved, context);
2014
- const labels = authored.label && authored.label.trim() !== "" ? [createCustomLabel(authored.label, sheetPositionMm, context.frame, authored.id)] : createCoordinateLabels(resolved, sheetPositionMm, authored.id);
2015
- assertMarkFits(sheetPositionMm, labels, context.frame, authored.id);
2016
- marks.push({
2017
- id: authored.id,
2018
- mgrs: resolved.normalized,
2019
- position: [resolved.position[0], resolved.position[1]],
2020
- sheetPositionMm
2021
- });
2022
- const elements = [
2023
- createCrosshairAxis([{
2024
- xMm: sheetPositionMm.xMm - CROSSHAIR_HALF_SIZE_MM,
2025
- yMm: sheetPositionMm.yMm
2026
- }, {
2027
- xMm: sheetPositionMm.xMm + CROSSHAIR_HALF_SIZE_MM,
2028
- yMm: sheetPositionMm.yMm
2029
- }], authored.id, "horizontal"),
2030
- createCrosshairAxis([{
2031
- xMm: sheetPositionMm.xMm,
2032
- yMm: sheetPositionMm.yMm - CROSSHAIR_HALF_SIZE_MM
2033
- }, {
2034
- xMm: sheetPositionMm.xMm,
2035
- yMm: sheetPositionMm.yMm + CROSSHAIR_HALF_SIZE_MM
2036
- }], authored.id, "vertical"),
2037
- ...labels
2038
- ];
2039
- graphics.push({
2040
- id: authored.id,
2041
- elements
2042
- });
2043
- }
2044
- if (!hasDistinctPair(marks)) throw new RangeError("Registration requires marks at two distinct positions");
2003
+ function expandFrame(frame, deltaMm) {
2004
+ if (deltaMm === 0) return frame;
2045
2005
  return {
2046
- layer: {
2047
- id: "registration-marks-0",
2048
- graphics,
2049
- attributes: { "data-registration-marks": marks.length }
2050
- },
2051
- marks
2006
+ xMm: frame.xMm - deltaMm,
2007
+ yMm: frame.yMm - deltaMm,
2008
+ widthMm: frame.widthMm + 2 * deltaMm,
2009
+ heightMm: frame.heightMm + 2 * deltaMm
2052
2010
  };
2053
2011
  }
2054
- //#endregion
2055
- //#region src/printer-calibration.ts
2056
- const DEFAULT_LENGTH_MM = 100;
2057
- const TICK_HALF_HEIGHT_MM = 2;
2058
- const LABEL_OFFSET_MM = 2.5;
2059
- const STROKE_WIDTH_MM = DEFAULT_LINE_STROKE_WIDTH_MM;
2060
- function line(points, attributes) {
2061
- return createSceneLine(points, "#000000", { attributes });
2062
- }
2063
- function renderPrinterCalibration(request, page, frame, reservedBottomMm = 0) {
2064
- const lengthMm = request.lengthMm ?? DEFAULT_LENGTH_MM;
2065
- requirePositiveFinite(lengthMm, "Printer-calibration length");
2066
- const centerX = page.widthMm / 2;
2067
- const frameBottom = frame.yMm + frame.heightMm;
2068
- const layoutBottom = page.heightMm - reservedBottomMm;
2069
- const yMm = frameBottom + (layoutBottom - frameBottom) / 2;
2070
- const startX = centerX - lengthMm / 2;
2071
- const endX = centerX + lengthMm / 2;
2072
- const label = createRegularSceneText({
2073
- text: `${lengthMm} mm`,
2074
- xMm: centerX,
2075
- yMm: yMm - LABEL_OFFSET_MM,
2076
- sizeCssPixels: 6,
2077
- color: "#000000",
2078
- attributes: { "data-printer-calibration-label": lengthMm }
2079
- });
2080
- const strokeEdge = STROKE_WIDTH_MM / 2;
2081
- const fitsHorizontally = startX - strokeEdge >= 0 && endX + strokeEdge <= page.widthMm;
2082
- const labelLeft = label.position.xMm - label.widthMm / 2;
2083
- const labelRight = label.position.xMm + label.widthMm / 2;
2084
- const contentTop = Math.min(label.position.yMm - label.heightMm / 2, yMm - TICK_HALF_HEIGHT_MM - strokeEdge);
2085
- const contentBottom = Math.max(label.position.yMm + label.heightMm / 2, yMm + TICK_HALF_HEIGHT_MM + strokeEdge);
2086
- 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");
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]]);
2087
2020
  return {
2088
- id: "printer-calibration-0",
2089
- graphics: [{
2090
- id: "printer-calibration",
2091
- elements: [
2092
- line([{
2093
- xMm: startX,
2094
- yMm
2095
- }, {
2096
- xMm: endX,
2097
- yMm
2098
- }], { "data-printer-calibration-length-mm": lengthMm }),
2099
- line([{
2100
- xMm: startX,
2101
- yMm: yMm - TICK_HALF_HEIGHT_MM
2102
- }, {
2103
- xMm: startX,
2104
- yMm: yMm + TICK_HALF_HEIGHT_MM
2105
- }], { "data-printer-calibration-tick": "start" }),
2106
- line([{
2107
- xMm: endX,
2108
- yMm: yMm - TICK_HALF_HEIGHT_MM
2109
- }, {
2110
- xMm: endX,
2111
- yMm: yMm + TICK_HALF_HEIGHT_MM
2112
- }], { "data-printer-calibration-tick": "end" }),
2113
- label
2114
- ]
2115
- }]
2021
+ intersects: points.some((point) => pointInside(point, outerFrame)) || segments.some(([start, end]) => segmentIntersectsFrame(start, end, outerFrame)),
2022
+ inside
2116
2023
  };
2117
2024
  }
2118
- //#endregion
2119
- //#region src/raster-plan.ts
2120
- function resolvePage(input) {
2121
- requirePositiveFinite(input.widthMm, "Page width");
2122
- requirePositiveFinite(input.heightMm, "Page height");
2123
- if (input.orientation === "landscape" && input.widthMm < input.heightMm || input.orientation === "portrait" && input.widthMm > input.heightMm) return {
2124
- widthMm: input.heightMm,
2125
- heightMm: input.widthMm
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
2126
2039
  };
2127
- return {
2128
- widthMm: input.widthMm,
2129
- heightMm: input.heightMm
2040
+ if (!visibility.every((item) => item.inside)) return {
2041
+ code: "graphic-clipped",
2042
+ layerId,
2043
+ graphicId
2130
2044
  };
2131
2045
  }
2132
- function resolveFrame(request, page) {
2133
- if (request.mapFrame) {
2134
- if (request.page.marginMm !== void 0) throw new RangeError("Specify either a page margin or an explicit map frame, not both");
2135
- const { xMm, yMm, widthMm, heightMm } = request.mapFrame;
2136
- requirePositiveFinite(widthMm, "Map-frame width");
2137
- requirePositiveFinite(heightMm, "Map-frame height");
2138
- if (!Number.isFinite(xMm) || xMm < 0 || !Number.isFinite(yMm) || yMm < 0) throw new RangeError("Map-frame position must be finite and non-negative");
2139
- if (xMm + widthMm > page.widthMm || yMm + heightMm > page.heightMm) throw new RangeError("The map frame must fit within the physical page");
2140
- return {
2141
- xMm,
2142
- yMm,
2143
- widthMm,
2144
- heightMm
2145
- };
2146
- }
2147
- const marginMm = request.page.marginMm ?? 0;
2148
- if (!Number.isFinite(marginMm) || marginMm < 0) throw new RangeError("Page margin must be a finite non-negative number");
2149
- const widthMm = page.widthMm - 2 * marginMm;
2150
- const heightMm = page.heightMm - 2 * marginMm;
2151
- if (widthMm <= 0 || heightMm <= 0) throw new RangeError("Page margins must leave a positive map frame");
2152
- return {
2153
- xMm: marginMm,
2154
- yMm: marginMm,
2155
- widthMm,
2156
- heightMm
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
+ };
2099
+ }
2100
+ const graphicsStyle = {
2101
+ color: portrayal.symbolColor,
2102
+ strokeWidth: portrayal.strokeWidthCssPixels,
2103
+ strokeDash: [...portrayal.strokeDashCssPixels]
2157
2104
  };
2158
- }
2159
- function resolveProjection(requested, center) {
2160
- const selected = geographicLibGridProjection.selectStandard(center);
2161
- if (requested === void 0 || requested === "auto") return selected;
2162
- if (requested.hemisphere !== selected.hemisphere) throw new RangeError("The explicit projection hemisphere must contain the sheet center");
2163
- if (requested.kind === "ups" && selected.kind !== "ups") throw new RangeError("UPS can only be selected for a center in a polar UPS region");
2164
- return requested;
2165
- }
2166
- function epsgFor(crs) {
2167
- if (crs.kind === "ups") return crs.hemisphere === "north" ? 32661 : 32761;
2168
- return (crs.hemisphere === "north" ? 32600 : 32700) + crs.zone;
2169
- }
2170
- function resolveMapSheetGeometry(request) {
2171
- requirePositiveFinite(request.scaleDenominator, "Scale denominator");
2172
- const page = resolvePage(request.page);
2173
- const frame = resolveFrame(request, page);
2174
- const crs = resolveProjection(request.projection, request.center);
2175
- const center = geographicLibGridProjection.forward(crs, request.center);
2176
- if (!(center.pointScale > 0)) throw new Error("Projection point scale must be positive");
2177
- const projectedMetresPerMillimetre = request.scaleDenominator / 1e3 * center.pointScale;
2178
- const projectedWidth = frame.widthMm * projectedMetresPerMillimetre;
2179
- const projectedHeight = frame.heightMm * projectedMetresPerMillimetre;
2180
- return {
2181
- page,
2182
- center,
2183
- plan: {
2184
- crs,
2185
- epsg: epsgFor(crs),
2186
- frame,
2187
- projectedMetresPerMillimetre,
2188
- projectedBounds: {
2189
- left: center.easting - projectedWidth / 2,
2190
- bottom: center.northing - projectedHeight / 2,
2191
- right: center.easting + projectedWidth / 2,
2192
- top: center.northing + projectedHeight / 2
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
2193
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 });
2194
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`);
2149
+ return {
2150
+ graphic: {
2151
+ id: graphic.id,
2152
+ elements
2153
+ },
2154
+ warnings: [visibilityWarning(layerId, graphic.id, elements, context.frame)].filter((warning) => warning !== void 0)
2195
2155
  };
2196
2156
  }
2197
- function resolveMapSheetRasterPlan(request) {
2198
- return resolveMapSheetGeometry(request).plan;
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();
2166
+ return {
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);
2184
+ }
2185
+ return {
2186
+ id: authoredLayer.id,
2187
+ graphics
2188
+ };
2189
+ }),
2190
+ warnings,
2191
+ fontStyles: [...fontStyles],
2192
+ patterns
2193
+ };
2199
2194
  }
2200
- function mapSheetRasterPointToGeographic(plan, normalizedX, normalizedY) {
2201
- 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");
2202
- const bounds = plan.projectedBounds;
2203
- return geographicLibGridProjection.reverse(plan.crs, {
2204
- easting: bounds.left + normalizedX * (bounds.right - bounds.left),
2205
- northing: bounds.top - normalizedY * (bounds.top - bounds.bottom)
2206
- });
2195
+ function assertNever(value) {
2196
+ throw new Error(`Unsupported geometry: ${String(value)}`);
2207
2197
  }
2208
2198
  //#endregion
2209
- //#region src/raster-basemap.ts
2210
- const TESSELLATION_TOLERANCE_MM = 1e-6;
2211
- const LOW_DPI_THRESHOLD = 150;
2212
- const DPI_ANISOTROPY_THRESHOLD = .01;
2213
- function renderRasterBasemapLayers(basemap) {
2214
- return basemap.layers.map((layer) => ({
2215
- id: `raster-basemap-${layer.id}`,
2216
- attributes: {
2217
- "data-raster-layer": layer.id,
2218
- "data-opacity": layer.opacity
2219
- },
2220
- graphics: layer.tiles.map((tile) => ({
2221
- id: tile.id,
2222
- elements: [{
2223
- kind: "raster-image",
2224
- mediaType: tile.mediaType,
2225
- data: tile.data,
2226
- frame: { ...tile.frame },
2227
- opacity: layer.opacity,
2228
- resourceId: `${layer.id}/${tile.id}`
2229
- }]
2230
- }))
2231
- }));
2232
- }
2233
- function requireStableId(value, label, ids) {
2234
- if (typeof value !== "string" || value.trim() === "") throw new RangeError(`${label} must be a non-blank stable ID`);
2235
- if (ids.has(value)) throw new RangeError(`Duplicate ${label.toLowerCase()}: ${value}`);
2236
- ids.add(value);
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}`);
2237
2204
  }
2238
- function readUint32(bytes, offset, littleEndian = false) {
2239
- if (offset < 0 || offset + 4 > bytes.length) throw new RangeError("Malformed image data");
2240
- return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(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;
2241
2213
  }
2242
- function readUint16(bytes, offset, littleEndian = false) {
2243
- if (offset < 0 || offset + 2 > bytes.length) throw new RangeError("Malformed image data");
2244
- return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint16(offset, littleEndian);
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");
2245
2216
  }
2246
- function ascii(bytes, offset, length) {
2247
- if (offset < 0 || offset + length > bytes.length) throw new RangeError("Malformed image data");
2248
- return String.fromCharCode(...bytes.subarray(offset, offset + length));
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;
2221
+ return {
2222
+ easting: coordinate.easting,
2223
+ northing: coordinate.northing + 1e-6
2224
+ };
2249
2225
  }
2250
- function inspectPng(bytes) {
2251
- if (bytes.length < 33 || [
2252
- 137,
2253
- 80,
2254
- 78,
2255
- 71,
2256
- 13,
2257
- 10,
2258
- 26,
2259
- 10
2260
- ].some((value, index) => bytes[index] !== value)) throw new RangeError("Malformed PNG image");
2261
- if (readUint32(bytes, 8) !== 13 || ascii(bytes, 12, 4) !== "IHDR") throw new RangeError("Malformed PNG image: IHDR must be first");
2262
- const width = readUint32(bytes, 16);
2263
- const height = readUint32(bytes, 20);
2264
- let offset = 8;
2265
- let ended = false;
2266
- while (offset + 12 <= bytes.length) {
2267
- const length = readUint32(bytes, offset);
2268
- const type = ascii(bytes, offset + 4, 4);
2269
- const next = offset + 12 + length;
2270
- if (next > bytes.length) throw new RangeError("Malformed PNG image chunk");
2271
- if (type === "acTL") throw new RangeError("APNG images are not supported");
2272
- offset = next;
2273
- if (type === "IEND") {
2274
- ended = true;
2275
- break;
2276
- }
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);
2277
2259
  }
2278
- if (!ended || offset !== bytes.length || width === 0 || height === 0) throw new RangeError("Malformed PNG image");
2260
+ }
2261
+ function normalizeMgrsReference(reference) {
2262
+ return parseMgrsReference(reference).normalized;
2263
+ }
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);
2279
2267
  return {
2280
- width,
2281
- height
2268
+ crs,
2269
+ easting,
2270
+ northing
2282
2271
  };
2283
2272
  }
2284
- function readExifOrientation(bytes, start, length) {
2285
- if (length < 6 || ascii(bytes, start, 6) !== "Exif\0\0") return void 0;
2286
- if (length < 14) throw new RangeError("Malformed JPEG EXIF data");
2287
- const tiff = start + 6;
2288
- const byteOrder = ascii(bytes, tiff, 2);
2289
- if (byteOrder !== "II" && byteOrder !== "MM") throw new RangeError("Malformed JPEG EXIF data");
2290
- const littleEndian = byteOrder === "II";
2291
- if (readUint16(bytes, tiff + 2, littleEndian) !== 42) throw new RangeError("Malformed JPEG EXIF data");
2292
- const ifd = tiff + readUint32(bytes, tiff + 4, littleEndian);
2293
- if (ifd + 2 > start + length) throw new RangeError("Malformed JPEG EXIF data");
2294
- const entries = readUint16(bytes, ifd, littleEndian);
2295
- for (let index = 0; index < entries; index += 1) {
2296
- const entry = ifd + 2 + index * 12;
2297
- if (entry + 12 > start + length) throw new RangeError("Malformed JPEG EXIF data");
2298
- if (readUint16(bytes, entry, littleEndian) === 274) {
2299
- if (readUint16(bytes, entry + 2, littleEndian) !== 3 || readUint32(bytes, entry + 4, littleEndian) !== 1) throw new RangeError("Malformed JPEG EXIF orientation");
2300
- return readUint16(bytes, entry + 8, littleEndian);
2301
- }
2302
- }
2273
+ /** Convert an MGRS cell to its southwest intersection in GeoJSON coordinate order. */
2274
+ function mgrsToGeographic(reference) {
2275
+ return parseMgrsReference(reference).position;
2303
2276
  }
2304
- function inspectJpeg(bytes) {
2305
- if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216 || bytes.at(-2) !== 255 || bytes.at(-1) !== 217) throw new RangeError("Malformed JPEG image");
2306
- let offset = 2;
2307
- let dimensions;
2308
- let sawScan = false;
2309
- while (offset < bytes.length - 2) {
2310
- if (bytes[offset] !== 255) throw new RangeError("Malformed JPEG marker");
2311
- while (bytes[offset] === 255) offset += 1;
2312
- const marker = bytes[offset++];
2313
- if (marker === 217) break;
2314
- if (marker === 218) {
2315
- const segmentLength = readUint16(bytes, offset);
2316
- if (segmentLength < 2 || offset + segmentLength > bytes.length - 2) throw new RangeError("Malformed JPEG scan header");
2317
- sawScan = true;
2318
- break;
2319
- }
2320
- if (marker === 1 || marker >= 208 && marker <= 215) continue;
2321
- const segmentLength = readUint16(bytes, offset);
2322
- if (segmentLength < 2 || offset + segmentLength > bytes.length) throw new RangeError("Malformed JPEG segment");
2323
- const dataStart = offset + 2;
2324
- const dataLength = segmentLength - 2;
2325
- if (marker === 225) {
2326
- const orientation = readExifOrientation(bytes, dataStart, dataLength);
2327
- if (orientation !== void 0 && orientation !== 1) throw new RangeError(`JPEG EXIF orientation ${orientation} is not supported`);
2328
- }
2329
- if (marker === 192 || marker === 194) {
2330
- if (dataLength < 6) throw new RangeError("Malformed JPEG dimensions");
2331
- dimensions = {
2332
- height: readUint16(bytes, dataStart + 1),
2333
- width: readUint16(bytes, dataStart + 3)
2334
- };
2335
- } else if (marker >= 192 && marker <= 207 && ![
2336
- 196,
2337
- 200,
2338
- 204
2339
- ].includes(marker)) throw new RangeError("Only baseline and progressive JPEG images are supported");
2340
- offset += segmentLength;
2341
- }
2342
- if (!dimensions || dimensions.width === 0 || dimensions.height === 0 || !sawScan) throw new RangeError("Malformed JPEG image: dimensions are missing");
2343
- return dimensions;
2277
+ function projectedToMgrs(coordinate, precision = 5) {
2278
+ assertPrecision(precision);
2279
+ return geographicLibGridProjection.formatMgrs(coordinate.crs, pointForMgrsFormatting(coordinate, precision), precision);
2344
2280
  }
2345
- function inspectImage(tile) {
2346
- if (!(tile.data instanceof Uint8Array) || tile.data.length === 0) throw new RangeError(`Raster tile ${tile.id} image bytes must be non-empty`);
2347
- 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`);
2348
- const actual = tile.mediaType === "image/png" ? inspectPng(tile.data) : tile.mediaType === "image/jpeg" ? inspectJpeg(tile.data) : void 0;
2349
- if (!actual) throw new RangeError(`Raster tile ${tile.id} media type is not supported`);
2350
- if (actual.width !== tile.pixelWidth || actual.height !== tile.pixelHeight) {
2351
- const format = tile.mediaType === "image/png" ? "PNG" : "JPEG";
2352
- throw new RangeError(`Raster tile ${tile.id} declared dimensions ${tile.pixelWidth}x${tile.pixelHeight} do not match ${format} dimensions ${actual.width}x${actual.height}`);
2353
- }
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);
2354
2288
  }
2355
- function clustered(values) {
2356
- const sorted = [...values].sort((left, right) => left - right);
2357
- const result = [];
2358
- for (const value of sorted) if (result.length === 0 || value - result[result.length - 1] > TESSELLATION_TOLERANCE_MM) result.push(value);
2359
- return result;
2289
+ function snapUpOnHalf(value, interval) {
2290
+ return Math.floor(value / interval + .5) * interval;
2360
2291
  }
2361
- function validateTessellation(layer, frame) {
2362
- const right = frame.xMm + frame.widthMm;
2363
- const bottom = frame.yMm + frame.heightMm;
2364
- for (const tile of layer.tiles) {
2365
- const rectangle = tile.frame;
2366
- 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`);
2367
- }
2368
- const xs = clustered([
2369
- frame.xMm,
2370
- right,
2371
- ...layer.tiles.flatMap((tile) => [tile.frame.xMm, tile.frame.xMm + tile.frame.widthMm])
2372
- ]);
2373
- const ys = clustered([
2374
- frame.yMm,
2375
- bottom,
2376
- ...layer.tiles.flatMap((tile) => [tile.frame.yMm, tile.frame.yMm + tile.frame.heightMm])
2377
- ]);
2378
- for (let xIndex = 0; xIndex < xs.length - 1; xIndex += 1) for (let yIndex = 0; yIndex < ys.length - 1; yIndex += 1) {
2379
- const x = (xs[xIndex] + xs[xIndex + 1]) / 2;
2380
- const y = (ys[yIndex] + ys[yIndex + 1]) / 2;
2381
- if (x < frame.xMm || x > right || y < frame.yMm || y > bottom) continue;
2382
- 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`);
2383
- }
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));
2384
2301
  }
2385
- function validateAttribution(attribution) {
2386
- return attribution.map((entry) => {
2387
- if (typeof entry.text !== "string" || entry.text.trim() === "") throw new RangeError("Raster attribution text must be non-blank");
2388
- if (typeof entry.required !== "boolean") throw new RangeError("Raster attribution requiredness must be explicit");
2389
- return {
2390
- text: entry.text,
2391
- required: entry.required
2392
- };
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
2325
+ }
2393
2326
  });
2394
2327
  }
2395
- function resolveRasterBasemap(basemap, frame) {
2396
- if (basemap.layers.length === 0) throw new RangeError("A raster basemap requires at least one layer");
2397
- const layerIds = /* @__PURE__ */ new Set();
2398
- const tileIds = /* @__PURE__ */ new Set();
2399
- const attributionTexts = /* @__PURE__ */ new Set();
2400
- const warnings = [];
2401
- const allAttribution = [];
2402
- const layers = basemap.layers.map((layer) => {
2403
- requireStableId(layer.id, "Raster layer ID", layerIds);
2404
- 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`);
2405
- if (layer.tiles.length === 0) throw new RangeError(`Raster layer ${layer.id} requires at least one tile`);
2406
- const attribution = validateAttribution(layer.attribution).filter((entry) => {
2407
- if (attributionTexts.has(entry.text)) return false;
2408
- attributionTexts.add(entry.text);
2409
- return true;
2410
- });
2411
- allAttribution.push(...attribution);
2412
- for (const tile of layer.tiles) {
2413
- requireStableId(tile.id, "Raster tile ID", tileIds);
2414
- inspectImage(tile);
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
2415
2352
  }
2416
- validateTessellation(layer, frame);
2417
- const tiles = layer.tiles.map((tile) => {
2418
- const effectiveHorizontalDpi = tile.pixelWidth * 25.4 / tile.frame.widthMm;
2419
- const effectiveVerticalDpi = tile.pixelHeight * 25.4 / tile.frame.heightMm;
2420
- if (effectiveHorizontalDpi < LOW_DPI_THRESHOLD || effectiveVerticalDpi < LOW_DPI_THRESHOLD) warnings.push({
2421
- code: "low-raster-dpi",
2422
- layerId: layer.id,
2423
- tileId: tile.id,
2424
- effectiveHorizontalDpi,
2425
- effectiveVerticalDpi,
2426
- thresholdDpi: LOW_DPI_THRESHOLD
2427
- });
2428
- const relativeDifference = Math.abs(effectiveHorizontalDpi - effectiveVerticalDpi) / Math.max(effectiveHorizontalDpi, effectiveVerticalDpi);
2429
- if (relativeDifference > DPI_ANISOTROPY_THRESHOLD) warnings.push({
2430
- code: "raster-dpi-anisotropy",
2431
- layerId: layer.id,
2432
- tileId: tile.id,
2433
- relativeDifference
2434
- });
2435
- return {
2436
- id: tile.id,
2437
- mediaType: tile.mediaType,
2438
- pixelWidth: tile.pixelWidth,
2439
- pixelHeight: tile.pixelHeight,
2440
- frame: { ...tile.frame },
2441
- effectiveHorizontalDpi,
2442
- effectiveVerticalDpi
2443
- };
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
2444
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");
2445
2539
  return {
2446
- resolved: {
2447
- id: layer.id,
2448
- opacity: layer.opacity,
2449
- tiles: [...layer.tiles]
2450
- },
2451
- metadata: {
2452
- id: layer.id,
2453
- opacity: layer.opacity,
2454
- attribution,
2455
- tiles
2456
- }
2540
+ xMm,
2541
+ yMm,
2542
+ widthMm,
2543
+ heightMm
2457
2544
  };
2458
- });
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");
2459
2551
  return {
2460
- layers: layers.map((layer) => layer.resolved),
2461
- metadata: { layers: layers.map((layer) => layer.metadata) },
2462
- warnings,
2463
- attribution: allAttribution
2552
+ xMm: marginMm,
2553
+ yMm: marginMm,
2554
+ widthMm,
2555
+ heightMm
2464
2556
  };
2465
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
+ }
2466
2607
  //#endregion
2467
2608
  //#region src/create-tactical-map-sheet.ts
2468
2609
  const FOOTPRINT_SEGMENTS_PER_EDGE = 16;
@@ -2570,7 +2711,8 @@ function createTacticalMapSheetDocument(request) {
2570
2711
  frame: mapFrame,
2571
2712
  footprintRing,
2572
2713
  groundMetersPerCssPixel: request.scaleDenominator * MILLIMETRES_PER_CSS_PIXEL / 1e3,
2573
- pointSymbols: request.pointSymbols
2714
+ pointSymbols: request.pointSymbols,
2715
+ notes: request.notes
2574
2716
  });
2575
2717
  const renderedGrid = request.grid && renderMgrsGrid(request.grid, {
2576
2718
  crs,
@@ -2655,4 +2797,4 @@ function createTacticalMapSheet(request) {
2655
2797
  return createTacticalMapSheetDocument(request).result;
2656
2798
  }
2657
2799
  //#endregion
2658
- 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 };