@loaders.gl/terrain 4.0.0-beta.2 → 4.0.0-beta.3

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.
Files changed (69) hide show
  1. package/dist/dist.dev.js +1214 -0
  2. package/dist/index.cjs +1020 -0
  3. package/dist/{esm/index.js → index.js} +4 -4
  4. package/dist/index.js.map +1 -0
  5. package/dist/lib/decode-quantized-mesh.js.map +1 -0
  6. package/dist/lib/delatin/index.js.map +1 -0
  7. package/dist/lib/helpers/skirt.js.map +1 -0
  8. package/dist/{esm/lib → lib}/parse-quantized-mesh.js +2 -2
  9. package/dist/lib/parse-quantized-mesh.js.map +1 -0
  10. package/dist/{esm/lib → lib}/parse-terrain.js +2 -2
  11. package/dist/lib/parse-terrain.js.map +1 -0
  12. package/dist/lib/utils/version.js +2 -0
  13. package/dist/lib/utils/version.js.map +1 -0
  14. package/dist/{esm/quantized-mesh-loader.js → quantized-mesh-loader.js} +1 -1
  15. package/dist/quantized-mesh-loader.js.map +1 -0
  16. package/dist/quantized-mesh-worker.js +133 -27
  17. package/dist/{esm/terrain-loader.js → terrain-loader.js} +1 -1
  18. package/dist/terrain-loader.js.map +1 -0
  19. package/dist/terrain-worker.js +133 -27
  20. package/dist/{esm/workers → workers}/quantized-mesh-worker.js +1 -1
  21. package/dist/workers/quantized-mesh-worker.js.map +1 -0
  22. package/dist/{esm/workers → workers}/terrain-worker.js +1 -1
  23. package/dist/workers/terrain-worker.js.map +1 -0
  24. package/package.json +17 -9
  25. package/dist/bundle.d.ts +0 -2
  26. package/dist/bundle.d.ts.map +0 -1
  27. package/dist/dist.min.js +0 -1186
  28. package/dist/es5/bundle.js +0 -6
  29. package/dist/es5/bundle.js.map +0 -1
  30. package/dist/es5/index.js +0 -88
  31. package/dist/es5/index.js.map +0 -1
  32. package/dist/es5/lib/decode-quantized-mesh.js +0 -250
  33. package/dist/es5/lib/decode-quantized-mesh.js.map +0 -1
  34. package/dist/es5/lib/delatin/index.js +0 -408
  35. package/dist/es5/lib/delatin/index.js.map +0 -1
  36. package/dist/es5/lib/helpers/skirt.js +0 -105
  37. package/dist/es5/lib/helpers/skirt.js.map +0 -1
  38. package/dist/es5/lib/parse-quantized-mesh.js +0 -95
  39. package/dist/es5/lib/parse-quantized-mesh.js.map +0 -1
  40. package/dist/es5/lib/parse-terrain.js +0 -152
  41. package/dist/es5/lib/parse-terrain.js.map +0 -1
  42. package/dist/es5/lib/utils/version.js +0 -9
  43. package/dist/es5/lib/utils/version.js.map +0 -1
  44. package/dist/es5/quantized-mesh-loader.js +0 -24
  45. package/dist/es5/quantized-mesh-loader.js.map +0 -1
  46. package/dist/es5/terrain-loader.js +0 -32
  47. package/dist/es5/terrain-loader.js.map +0 -1
  48. package/dist/es5/workers/quantized-mesh-worker.js +0 -6
  49. package/dist/es5/workers/quantized-mesh-worker.js.map +0 -1
  50. package/dist/es5/workers/terrain-worker.js +0 -6
  51. package/dist/es5/workers/terrain-worker.js.map +0 -1
  52. package/dist/esm/bundle.js +0 -4
  53. package/dist/esm/bundle.js.map +0 -1
  54. package/dist/esm/index.js.map +0 -1
  55. package/dist/esm/lib/decode-quantized-mesh.js.map +0 -1
  56. package/dist/esm/lib/delatin/index.js.map +0 -1
  57. package/dist/esm/lib/helpers/skirt.js.map +0 -1
  58. package/dist/esm/lib/parse-quantized-mesh.js.map +0 -1
  59. package/dist/esm/lib/parse-terrain.js.map +0 -1
  60. package/dist/esm/lib/utils/version.js +0 -2
  61. package/dist/esm/lib/utils/version.js.map +0 -1
  62. package/dist/esm/quantized-mesh-loader.js.map +0 -1
  63. package/dist/esm/terrain-loader.js.map +0 -1
  64. package/dist/esm/workers/quantized-mesh-worker.js.map +0 -1
  65. package/dist/esm/workers/terrain-worker.js.map +0 -1
  66. package/src/bundle.ts +0 -4
  67. /package/dist/{esm/lib → lib}/decode-quantized-mesh.js +0 -0
  68. /package/dist/{esm/lib → lib}/delatin/index.js +0 -0
  69. /package/dist/{esm/lib → lib}/helpers/skirt.js +0 -0
@@ -0,0 +1,1214 @@
1
+ (function webpackUniversalModuleDefinition(root, factory) {
2
+ if (typeof exports === 'object' && typeof module === 'object')
3
+ module.exports = factory();
4
+ else if (typeof define === 'function' && define.amd) define([], factory);
5
+ else if (typeof exports === 'object') exports['loader'] = factory();
6
+ else root['loader'] = factory();})(globalThis, function () {
7
+ "use strict";
8
+ var __exports__ = (() => {
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
26
+
27
+ // src/index.ts
28
+ var src_exports = {};
29
+ __export(src_exports, {
30
+ QuantizedMeshLoader: () => QuantizedMeshLoader2,
31
+ QuantizedMeshWorkerLoader: () => QuantizedMeshLoader,
32
+ TerrainLoader: () => TerrainLoader2,
33
+ TerrainWorkerLoader: () => TerrainLoader,
34
+ parseTerrain: () => parseTerrain
35
+ });
36
+
37
+ // ../loader-utils/src/loader-types.ts
38
+ async function parseFromContext(data, loaders, options, context) {
39
+ return context._parse(data, loaders, options, context);
40
+ }
41
+
42
+ // ../loader-utils/src/lib/binary-utils/array-buffer-utils.ts
43
+ function concatenateTypedArrays(...typedArrays) {
44
+ const arrays = typedArrays;
45
+ const TypedArrayConstructor = arrays && arrays.length > 1 && arrays[0].constructor || null;
46
+ if (!TypedArrayConstructor) {
47
+ throw new Error('"concatenateTypedArrays" - incorrect quantity of arguments or arguments have incompatible data types');
48
+ }
49
+ const sumLength = arrays.reduce((acc, value) => acc + value.length, 0);
50
+ const result = new TypedArrayConstructor(sumLength);
51
+ let offset = 0;
52
+ for (const array of arrays) {
53
+ result.set(array, offset);
54
+ offset += array.length;
55
+ }
56
+ return result;
57
+ }
58
+
59
+ // ../schema/src/lib/mesh/mesh-utils.ts
60
+ function getMeshBoundingBox(attributes) {
61
+ let minX = Infinity;
62
+ let minY = Infinity;
63
+ let minZ = Infinity;
64
+ let maxX = -Infinity;
65
+ let maxY = -Infinity;
66
+ let maxZ = -Infinity;
67
+ const positions = attributes.POSITION ? attributes.POSITION.value : [];
68
+ const len = positions && positions.length;
69
+ for (let i = 0; i < len; i += 3) {
70
+ const x = positions[i];
71
+ const y = positions[i + 1];
72
+ const z = positions[i + 2];
73
+ minX = x < minX ? x : minX;
74
+ minY = y < minY ? y : minY;
75
+ minZ = z < minZ ? z : minZ;
76
+ maxX = x > maxX ? x : maxX;
77
+ maxY = y > maxY ? y : maxY;
78
+ maxZ = z > maxZ ? z : maxZ;
79
+ }
80
+ return [[minX, minY, minZ], [maxX, maxY, maxZ]];
81
+ }
82
+
83
+ // src/lib/decode-quantized-mesh.ts
84
+ var QUANTIZED_MESH_HEADER = /* @__PURE__ */ new Map([["centerX", Float64Array.BYTES_PER_ELEMENT], ["centerY", Float64Array.BYTES_PER_ELEMENT], ["centerZ", Float64Array.BYTES_PER_ELEMENT], ["minHeight", Float32Array.BYTES_PER_ELEMENT], ["maxHeight", Float32Array.BYTES_PER_ELEMENT], ["boundingSphereCenterX", Float64Array.BYTES_PER_ELEMENT], ["boundingSphereCenterY", Float64Array.BYTES_PER_ELEMENT], ["boundingSphereCenterZ", Float64Array.BYTES_PER_ELEMENT], ["boundingSphereRadius", Float64Array.BYTES_PER_ELEMENT], ["horizonOcclusionPointX", Float64Array.BYTES_PER_ELEMENT], ["horizonOcclusionPointY", Float64Array.BYTES_PER_ELEMENT], ["horizonOcclusionPointZ", Float64Array.BYTES_PER_ELEMENT]]);
85
+ function decodeZigZag(value) {
86
+ return value >> 1 ^ -(value & 1);
87
+ }
88
+ function decodeHeader(dataView) {
89
+ let position = 0;
90
+ const header = {};
91
+ for (const [key, bytesCount] of QUANTIZED_MESH_HEADER) {
92
+ const getter = bytesCount === 8 ? dataView.getFloat64 : dataView.getFloat32;
93
+ header[key] = getter.call(dataView, position, true);
94
+ position += bytesCount;
95
+ }
96
+ return {
97
+ header,
98
+ headerEndPosition: position
99
+ };
100
+ }
101
+ function decodeVertexData(dataView, headerEndPosition) {
102
+ let position = headerEndPosition;
103
+ const elementsPerVertex = 3;
104
+ const vertexCount = dataView.getUint32(position, true);
105
+ const vertexData = new Uint16Array(vertexCount * elementsPerVertex);
106
+ position += Uint32Array.BYTES_PER_ELEMENT;
107
+ const bytesPerArrayElement = Uint16Array.BYTES_PER_ELEMENT;
108
+ const elementArrayLength = vertexCount * bytesPerArrayElement;
109
+ const uArrayStartPosition = position;
110
+ const vArrayStartPosition = uArrayStartPosition + elementArrayLength;
111
+ const heightArrayStartPosition = vArrayStartPosition + elementArrayLength;
112
+ let u = 0;
113
+ let v = 0;
114
+ let height = 0;
115
+ for (let i = 0; i < vertexCount; i++) {
116
+ u += decodeZigZag(dataView.getUint16(uArrayStartPosition + bytesPerArrayElement * i, true));
117
+ v += decodeZigZag(dataView.getUint16(vArrayStartPosition + bytesPerArrayElement * i, true));
118
+ height += decodeZigZag(dataView.getUint16(heightArrayStartPosition + bytesPerArrayElement * i, true));
119
+ vertexData[i] = u;
120
+ vertexData[i + vertexCount] = v;
121
+ vertexData[i + vertexCount * 2] = height;
122
+ }
123
+ position += elementArrayLength * 3;
124
+ return {
125
+ vertexData,
126
+ vertexDataEndPosition: position
127
+ };
128
+ }
129
+ function decodeIndex(buffer, position, indicesCount, bytesPerIndex, encoded = true) {
130
+ let indices;
131
+ if (bytesPerIndex === 2) {
132
+ indices = new Uint16Array(buffer, position, indicesCount);
133
+ } else {
134
+ indices = new Uint32Array(buffer, position, indicesCount);
135
+ }
136
+ if (!encoded) {
137
+ return indices;
138
+ }
139
+ let highest = 0;
140
+ for (let i = 0; i < indices.length; ++i) {
141
+ const code = indices[i];
142
+ indices[i] = highest - code;
143
+ if (code === 0) {
144
+ ++highest;
145
+ }
146
+ }
147
+ return indices;
148
+ }
149
+ function decodeTriangleIndices(dataView, vertexData, vertexDataEndPosition) {
150
+ let position = vertexDataEndPosition;
151
+ const elementsPerVertex = 3;
152
+ const vertexCount = vertexData.length / elementsPerVertex;
153
+ const bytesPerIndex = vertexCount > 65536 ? Uint32Array.BYTES_PER_ELEMENT : Uint16Array.BYTES_PER_ELEMENT;
154
+ if (position % bytesPerIndex !== 0) {
155
+ position += bytesPerIndex - position % bytesPerIndex;
156
+ }
157
+ const triangleCount = dataView.getUint32(position, true);
158
+ position += Uint32Array.BYTES_PER_ELEMENT;
159
+ const triangleIndicesCount = triangleCount * 3;
160
+ const triangleIndices = decodeIndex(dataView.buffer, position, triangleIndicesCount, bytesPerIndex);
161
+ position += triangleIndicesCount * bytesPerIndex;
162
+ return {
163
+ triangleIndicesEndPosition: position,
164
+ triangleIndices
165
+ };
166
+ }
167
+ function decodeEdgeIndices(dataView, vertexData, triangleIndicesEndPosition) {
168
+ let position = triangleIndicesEndPosition;
169
+ const elementsPerVertex = 3;
170
+ const vertexCount = vertexData.length / elementsPerVertex;
171
+ const bytesPerIndex = vertexCount > 65536 ? Uint32Array.BYTES_PER_ELEMENT : Uint16Array.BYTES_PER_ELEMENT;
172
+ const westVertexCount = dataView.getUint32(position, true);
173
+ position += Uint32Array.BYTES_PER_ELEMENT;
174
+ const westIndices = decodeIndex(dataView.buffer, position, westVertexCount, bytesPerIndex, false);
175
+ position += westVertexCount * bytesPerIndex;
176
+ const southVertexCount = dataView.getUint32(position, true);
177
+ position += Uint32Array.BYTES_PER_ELEMENT;
178
+ const southIndices = decodeIndex(dataView.buffer, position, southVertexCount, bytesPerIndex, false);
179
+ position += southVertexCount * bytesPerIndex;
180
+ const eastVertexCount = dataView.getUint32(position, true);
181
+ position += Uint32Array.BYTES_PER_ELEMENT;
182
+ const eastIndices = decodeIndex(dataView.buffer, position, eastVertexCount, bytesPerIndex, false);
183
+ position += eastVertexCount * bytesPerIndex;
184
+ const northVertexCount = dataView.getUint32(position, true);
185
+ position += Uint32Array.BYTES_PER_ELEMENT;
186
+ const northIndices = decodeIndex(dataView.buffer, position, northVertexCount, bytesPerIndex, false);
187
+ position += northVertexCount * bytesPerIndex;
188
+ return {
189
+ edgeIndicesEndPosition: position,
190
+ westIndices,
191
+ southIndices,
192
+ eastIndices,
193
+ northIndices
194
+ };
195
+ }
196
+ function decodeVertexNormalsExtension(extensionDataView) {
197
+ return new Uint8Array(extensionDataView.buffer, extensionDataView.byteOffset, extensionDataView.byteLength);
198
+ }
199
+ function decodeWaterMaskExtension(extensionDataView) {
200
+ return extensionDataView.buffer.slice(extensionDataView.byteOffset, extensionDataView.byteOffset + extensionDataView.byteLength);
201
+ }
202
+ function decodeExtensions(dataView, indicesEndPosition) {
203
+ const extensions = {};
204
+ if (dataView.byteLength <= indicesEndPosition) {
205
+ return {
206
+ extensions,
207
+ extensionsEndPosition: indicesEndPosition
208
+ };
209
+ }
210
+ let position = indicesEndPosition;
211
+ while (position < dataView.byteLength) {
212
+ const extensionId = dataView.getUint8(position, true);
213
+ position += Uint8Array.BYTES_PER_ELEMENT;
214
+ const extensionLength = dataView.getUint32(position, true);
215
+ position += Uint32Array.BYTES_PER_ELEMENT;
216
+ const extensionView = new DataView(dataView.buffer, position, extensionLength);
217
+ switch (extensionId) {
218
+ case 1: {
219
+ extensions.vertexNormals = decodeVertexNormalsExtension(extensionView);
220
+ break;
221
+ }
222
+ case 2: {
223
+ extensions.waterMask = decodeWaterMaskExtension(extensionView);
224
+ break;
225
+ }
226
+ default: {
227
+ }
228
+ }
229
+ position += extensionLength;
230
+ }
231
+ return {
232
+ extensions,
233
+ extensionsEndPosition: position
234
+ };
235
+ }
236
+ var DECODING_STEPS = {
237
+ header: 0,
238
+ vertices: 1,
239
+ triangleIndices: 2,
240
+ edgeIndices: 3,
241
+ extensions: 4
242
+ };
243
+ var DEFAULT_OPTIONS = {
244
+ maxDecodingStep: DECODING_STEPS.extensions
245
+ };
246
+ function decode(data, userOptions) {
247
+ const options = Object.assign({}, DEFAULT_OPTIONS, userOptions);
248
+ const view = new DataView(data);
249
+ const {
250
+ header,
251
+ headerEndPosition
252
+ } = decodeHeader(view);
253
+ if (options.maxDecodingStep < DECODING_STEPS.vertices) {
254
+ return {
255
+ header
256
+ };
257
+ }
258
+ const {
259
+ vertexData,
260
+ vertexDataEndPosition
261
+ } = decodeVertexData(view, headerEndPosition);
262
+ if (options.maxDecodingStep < DECODING_STEPS.triangleIndices) {
263
+ return {
264
+ header,
265
+ vertexData
266
+ };
267
+ }
268
+ const {
269
+ triangleIndices,
270
+ triangleIndicesEndPosition
271
+ } = decodeTriangleIndices(view, vertexData, vertexDataEndPosition);
272
+ if (options.maxDecodingStep < DECODING_STEPS.edgeIndices) {
273
+ return {
274
+ header,
275
+ vertexData,
276
+ triangleIndices
277
+ };
278
+ }
279
+ const {
280
+ westIndices,
281
+ southIndices,
282
+ eastIndices,
283
+ northIndices,
284
+ edgeIndicesEndPosition
285
+ } = decodeEdgeIndices(view, vertexData, triangleIndicesEndPosition);
286
+ if (options.maxDecodingStep < DECODING_STEPS.extensions) {
287
+ return {
288
+ header,
289
+ vertexData,
290
+ triangleIndices,
291
+ westIndices,
292
+ northIndices,
293
+ eastIndices,
294
+ southIndices
295
+ };
296
+ }
297
+ const {
298
+ extensions
299
+ } = decodeExtensions(view, edgeIndicesEndPosition);
300
+ return {
301
+ header,
302
+ vertexData,
303
+ triangleIndices,
304
+ westIndices,
305
+ northIndices,
306
+ eastIndices,
307
+ southIndices,
308
+ extensions
309
+ };
310
+ }
311
+
312
+ // src/lib/helpers/skirt.ts
313
+ function addSkirt(attributes, triangles, skirtHeight, outsideIndices) {
314
+ const outsideEdges = outsideIndices ? getOutsideEdgesFromIndices(outsideIndices, attributes.POSITION.value) : getOutsideEdgesFromTriangles(triangles);
315
+ const newPosition = new attributes.POSITION.value.constructor(outsideEdges.length * 6);
316
+ const newTexcoord0 = new attributes.TEXCOORD_0.value.constructor(outsideEdges.length * 4);
317
+ const newTriangles = new triangles.constructor(outsideEdges.length * 6);
318
+ for (let i = 0; i < outsideEdges.length; i++) {
319
+ const edge = outsideEdges[i];
320
+ updateAttributesForNewEdge({
321
+ edge,
322
+ edgeIndex: i,
323
+ attributes,
324
+ skirtHeight,
325
+ newPosition,
326
+ newTexcoord0,
327
+ newTriangles
328
+ });
329
+ }
330
+ attributes.POSITION.value = concatenateTypedArrays(attributes.POSITION.value, newPosition);
331
+ attributes.TEXCOORD_0.value = concatenateTypedArrays(attributes.TEXCOORD_0.value, newTexcoord0);
332
+ const resultTriangles = triangles instanceof Array ? triangles.concat(newTriangles) : concatenateTypedArrays(triangles, newTriangles);
333
+ return {
334
+ attributes,
335
+ triangles: resultTriangles
336
+ };
337
+ }
338
+ function getOutsideEdgesFromTriangles(triangles) {
339
+ const edges = [];
340
+ for (let i = 0; i < triangles.length; i += 3) {
341
+ edges.push([triangles[i], triangles[i + 1]]);
342
+ edges.push([triangles[i + 1], triangles[i + 2]]);
343
+ edges.push([triangles[i + 2], triangles[i]]);
344
+ }
345
+ edges.sort((a, b) => Math.min(...a) - Math.min(...b) || Math.max(...a) - Math.max(...b));
346
+ const outsideEdges = [];
347
+ let index = 0;
348
+ while (index < edges.length) {
349
+ if (edges[index][0] === edges[index + 1]?.[1] && edges[index][1] === edges[index + 1]?.[0]) {
350
+ index += 2;
351
+ } else {
352
+ outsideEdges.push(edges[index]);
353
+ index++;
354
+ }
355
+ }
356
+ return outsideEdges;
357
+ }
358
+ function getOutsideEdgesFromIndices(indices, position) {
359
+ indices.westIndices.sort((a, b) => position[3 * a + 1] - position[3 * b + 1]);
360
+ indices.eastIndices.sort((a, b) => position[3 * b + 1] - position[3 * a + 1]);
361
+ indices.southIndices.sort((a, b) => position[3 * b] - position[3 * a]);
362
+ indices.northIndices.sort((a, b) => position[3 * a] - position[3 * b]);
363
+ const edges = [];
364
+ for (const index in indices) {
365
+ const indexGroup = indices[index];
366
+ for (let i = 0; i < indexGroup.length - 1; i++) {
367
+ edges.push([indexGroup[i], indexGroup[i + 1]]);
368
+ }
369
+ }
370
+ return edges;
371
+ }
372
+ function updateAttributesForNewEdge({
373
+ edge,
374
+ edgeIndex,
375
+ attributes,
376
+ skirtHeight,
377
+ newPosition,
378
+ newTexcoord0,
379
+ newTriangles
380
+ }) {
381
+ const positionsLength = attributes.POSITION.value.length;
382
+ const vertex1Offset = edgeIndex * 2;
383
+ const vertex2Offset = edgeIndex * 2 + 1;
384
+ newPosition.set(attributes.POSITION.value.subarray(edge[0] * 3, edge[0] * 3 + 3), vertex1Offset * 3);
385
+ newPosition[vertex1Offset * 3 + 2] = newPosition[vertex1Offset * 3 + 2] - skirtHeight;
386
+ newPosition.set(attributes.POSITION.value.subarray(edge[1] * 3, edge[1] * 3 + 3), vertex2Offset * 3);
387
+ newPosition[vertex2Offset * 3 + 2] = newPosition[vertex2Offset * 3 + 2] - skirtHeight;
388
+ newTexcoord0.set(attributes.TEXCOORD_0.value.subarray(edge[0] * 2, edge[0] * 2 + 2), vertex1Offset * 2);
389
+ newTexcoord0.set(attributes.TEXCOORD_0.value.subarray(edge[1] * 2, edge[1] * 2 + 2), vertex2Offset * 2);
390
+ const triangle1Offset = edgeIndex * 2 * 3;
391
+ newTriangles[triangle1Offset] = edge[0];
392
+ newTriangles[triangle1Offset + 1] = positionsLength / 3 + vertex2Offset;
393
+ newTriangles[triangle1Offset + 2] = edge[1];
394
+ newTriangles[triangle1Offset + 3] = positionsLength / 3 + vertex2Offset;
395
+ newTriangles[triangle1Offset + 4] = edge[0];
396
+ newTriangles[triangle1Offset + 5] = positionsLength / 3 + vertex1Offset;
397
+ }
398
+
399
+ // src/lib/parse-quantized-mesh.ts
400
+ function parseQuantizedMesh(arrayBuffer, options = {}) {
401
+ const {
402
+ bounds
403
+ } = options;
404
+ const {
405
+ header,
406
+ vertexData,
407
+ triangleIndices: originalTriangleIndices,
408
+ westIndices,
409
+ northIndices,
410
+ eastIndices,
411
+ southIndices
412
+ } = decode(arrayBuffer, DECODING_STEPS.triangleIndices);
413
+ let triangleIndices = originalTriangleIndices;
414
+ let attributes = getMeshAttributes(vertexData, header, bounds);
415
+ const boundingBox = getMeshBoundingBox(attributes);
416
+ if (options?.skirtHeight) {
417
+ const {
418
+ attributes: newAttributes,
419
+ triangles: newTriangles
420
+ } = addSkirt(attributes, triangleIndices, options.skirtHeight, {
421
+ westIndices,
422
+ northIndices,
423
+ eastIndices,
424
+ southIndices
425
+ });
426
+ attributes = newAttributes;
427
+ triangleIndices = newTriangles;
428
+ }
429
+ return {
430
+ // Data return by this loader implementation
431
+ loaderData: {
432
+ header: {}
433
+ },
434
+ header: {
435
+ // @ts-ignore
436
+ vertexCount: triangleIndices.length,
437
+ boundingBox
438
+ },
439
+ // TODO
440
+ schema: void 0,
441
+ topology: "triangle-list",
442
+ mode: 4,
443
+ // TRIANGLES
444
+ indices: {
445
+ value: triangleIndices,
446
+ size: 1
447
+ },
448
+ attributes
449
+ };
450
+ }
451
+ function getMeshAttributes(vertexData, header, bounds) {
452
+ const {
453
+ minHeight,
454
+ maxHeight
455
+ } = header;
456
+ const [minX, minY, maxX, maxY] = bounds || [0, 0, 1, 1];
457
+ const xScale = maxX - minX;
458
+ const yScale = maxY - minY;
459
+ const zScale = maxHeight - minHeight;
460
+ const nCoords = vertexData.length / 3;
461
+ const positions = new Float32Array(nCoords * 3);
462
+ const texCoords = new Float32Array(nCoords * 2);
463
+ for (let i = 0; i < nCoords; i++) {
464
+ const x = vertexData[i] / 32767;
465
+ const y = vertexData[i + nCoords] / 32767;
466
+ const z = vertexData[i + nCoords * 2] / 32767;
467
+ positions[3 * i + 0] = x * xScale + minX;
468
+ positions[3 * i + 1] = y * yScale + minY;
469
+ positions[3 * i + 2] = z * zScale + minHeight;
470
+ texCoords[2 * i + 0] = x;
471
+ texCoords[2 * i + 1] = y;
472
+ }
473
+ return {
474
+ POSITION: {
475
+ value: positions,
476
+ size: 3
477
+ },
478
+ TEXCOORD_0: {
479
+ value: texCoords,
480
+ size: 2
481
+ }
482
+ // TODO: Parse normals if they exist in the file
483
+ // NORMAL: {}, - optional, but creates the high poly look with lighting
484
+ };
485
+ }
486
+
487
+ // ../../node_modules/@mapbox/martini/index.js
488
+ var Martini = class {
489
+ constructor(gridSize = 257) {
490
+ this.gridSize = gridSize;
491
+ const tileSize = gridSize - 1;
492
+ if (tileSize & tileSize - 1)
493
+ throw new Error(
494
+ `Expected grid size to be 2^n+1, got ${gridSize}.`
495
+ );
496
+ this.numTriangles = tileSize * tileSize * 2 - 2;
497
+ this.numParentTriangles = this.numTriangles - tileSize * tileSize;
498
+ this.indices = new Uint32Array(this.gridSize * this.gridSize);
499
+ this.coords = new Uint16Array(this.numTriangles * 4);
500
+ for (let i = 0; i < this.numTriangles; i++) {
501
+ let id = i + 2;
502
+ let ax = 0, ay = 0, bx = 0, by = 0, cx = 0, cy = 0;
503
+ if (id & 1) {
504
+ bx = by = cx = tileSize;
505
+ } else {
506
+ ax = ay = cy = tileSize;
507
+ }
508
+ while ((id >>= 1) > 1) {
509
+ const mx = ax + bx >> 1;
510
+ const my = ay + by >> 1;
511
+ if (id & 1) {
512
+ bx = ax;
513
+ by = ay;
514
+ ax = cx;
515
+ ay = cy;
516
+ } else {
517
+ ax = bx;
518
+ ay = by;
519
+ bx = cx;
520
+ by = cy;
521
+ }
522
+ cx = mx;
523
+ cy = my;
524
+ }
525
+ const k = i * 4;
526
+ this.coords[k + 0] = ax;
527
+ this.coords[k + 1] = ay;
528
+ this.coords[k + 2] = bx;
529
+ this.coords[k + 3] = by;
530
+ }
531
+ }
532
+ createTile(terrain) {
533
+ return new Tile(terrain, this);
534
+ }
535
+ };
536
+ var Tile = class {
537
+ constructor(terrain, martini) {
538
+ const size = martini.gridSize;
539
+ if (terrain.length !== size * size)
540
+ throw new Error(
541
+ `Expected terrain data of length ${size * size} (${size} x ${size}), got ${terrain.length}.`
542
+ );
543
+ this.terrain = terrain;
544
+ this.martini = martini;
545
+ this.errors = new Float32Array(terrain.length);
546
+ this.update();
547
+ }
548
+ update() {
549
+ const { numTriangles, numParentTriangles, coords, gridSize: size } = this.martini;
550
+ const { terrain, errors } = this;
551
+ for (let i = numTriangles - 1; i >= 0; i--) {
552
+ const k = i * 4;
553
+ const ax = coords[k + 0];
554
+ const ay = coords[k + 1];
555
+ const bx = coords[k + 2];
556
+ const by = coords[k + 3];
557
+ const mx = ax + bx >> 1;
558
+ const my = ay + by >> 1;
559
+ const cx = mx + my - ay;
560
+ const cy = my + ax - mx;
561
+ const interpolatedHeight = (terrain[ay * size + ax] + terrain[by * size + bx]) / 2;
562
+ const middleIndex = my * size + mx;
563
+ const middleError = Math.abs(interpolatedHeight - terrain[middleIndex]);
564
+ errors[middleIndex] = Math.max(errors[middleIndex], middleError);
565
+ if (i < numParentTriangles) {
566
+ const leftChildIndex = (ay + cy >> 1) * size + (ax + cx >> 1);
567
+ const rightChildIndex = (by + cy >> 1) * size + (bx + cx >> 1);
568
+ errors[middleIndex] = Math.max(errors[middleIndex], errors[leftChildIndex], errors[rightChildIndex]);
569
+ }
570
+ }
571
+ }
572
+ getMesh(maxError = 0) {
573
+ const { gridSize: size, indices } = this.martini;
574
+ const { errors } = this;
575
+ let numVertices = 0;
576
+ let numTriangles = 0;
577
+ const max = size - 1;
578
+ indices.fill(0);
579
+ function countElements(ax, ay, bx, by, cx, cy) {
580
+ const mx = ax + bx >> 1;
581
+ const my = ay + by >> 1;
582
+ if (Math.abs(ax - cx) + Math.abs(ay - cy) > 1 && errors[my * size + mx] > maxError) {
583
+ countElements(cx, cy, ax, ay, mx, my);
584
+ countElements(bx, by, cx, cy, mx, my);
585
+ } else {
586
+ indices[ay * size + ax] = indices[ay * size + ax] || ++numVertices;
587
+ indices[by * size + bx] = indices[by * size + bx] || ++numVertices;
588
+ indices[cy * size + cx] = indices[cy * size + cx] || ++numVertices;
589
+ numTriangles++;
590
+ }
591
+ }
592
+ countElements(0, 0, max, max, max, 0);
593
+ countElements(max, max, 0, 0, 0, max);
594
+ const vertices = new Uint16Array(numVertices * 2);
595
+ const triangles = new Uint32Array(numTriangles * 3);
596
+ let triIndex = 0;
597
+ function processTriangle(ax, ay, bx, by, cx, cy) {
598
+ const mx = ax + bx >> 1;
599
+ const my = ay + by >> 1;
600
+ if (Math.abs(ax - cx) + Math.abs(ay - cy) > 1 && errors[my * size + mx] > maxError) {
601
+ processTriangle(cx, cy, ax, ay, mx, my);
602
+ processTriangle(bx, by, cx, cy, mx, my);
603
+ } else {
604
+ const a = indices[ay * size + ax] - 1;
605
+ const b = indices[by * size + bx] - 1;
606
+ const c = indices[cy * size + cx] - 1;
607
+ vertices[2 * a] = ax;
608
+ vertices[2 * a + 1] = ay;
609
+ vertices[2 * b] = bx;
610
+ vertices[2 * b + 1] = by;
611
+ vertices[2 * c] = cx;
612
+ vertices[2 * c + 1] = cy;
613
+ triangles[triIndex++] = a;
614
+ triangles[triIndex++] = b;
615
+ triangles[triIndex++] = c;
616
+ }
617
+ }
618
+ processTriangle(0, 0, max, max, max, 0);
619
+ processTriangle(max, max, 0, 0, 0, max);
620
+ return { vertices, triangles };
621
+ }
622
+ };
623
+
624
+ // src/lib/delatin/index.ts
625
+ var Delatin = class {
626
+ constructor(data, width, height = width) {
627
+ this.data = data;
628
+ this.width = width;
629
+ this.height = height;
630
+ this.coords = [];
631
+ this.triangles = [];
632
+ this._halfedges = [];
633
+ this._candidates = [];
634
+ this._queueIndices = [];
635
+ this._queue = [];
636
+ this._errors = [];
637
+ this._rms = [];
638
+ this._pending = [];
639
+ this._pendingLen = 0;
640
+ this._rmsSum = 0;
641
+ const x1 = width - 1;
642
+ const y1 = height - 1;
643
+ const p0 = this._addPoint(0, 0);
644
+ const p1 = this._addPoint(x1, 0);
645
+ const p2 = this._addPoint(0, y1);
646
+ const p3 = this._addPoint(x1, y1);
647
+ const t0 = this._addTriangle(p3, p0, p2, -1, -1, -1);
648
+ this._addTriangle(p0, p3, p1, t0, -1, -1);
649
+ this._flush();
650
+ }
651
+ // refine the mesh until its maximum error gets below the given one
652
+ run(maxError = 1) {
653
+ while (this.getMaxError() > maxError) {
654
+ this.refine();
655
+ }
656
+ }
657
+ // refine the mesh with a single point
658
+ refine() {
659
+ this._step();
660
+ this._flush();
661
+ }
662
+ // max error of the current mesh
663
+ getMaxError() {
664
+ return this._errors[0];
665
+ }
666
+ // root-mean-square deviation of the current mesh
667
+ getRMSD() {
668
+ return this._rmsSum > 0 ? Math.sqrt(this._rmsSum / (this.width * this.height)) : 0;
669
+ }
670
+ // height value at a given position
671
+ heightAt(x, y) {
672
+ return this.data[this.width * y + x];
673
+ }
674
+ // rasterize and queue all triangles that got added or updated in _step
675
+ _flush() {
676
+ const coords = this.coords;
677
+ for (let i = 0; i < this._pendingLen; i++) {
678
+ const t = this._pending[i];
679
+ const a = 2 * this.triangles[t * 3 + 0];
680
+ const b = 2 * this.triangles[t * 3 + 1];
681
+ const c = 2 * this.triangles[t * 3 + 2];
682
+ this._findCandidate(coords[a], coords[a + 1], coords[b], coords[b + 1], coords[c], coords[c + 1], t);
683
+ }
684
+ this._pendingLen = 0;
685
+ }
686
+ // rasterize a triangle, find its max error, and queue it for processing
687
+ _findCandidate(p0x, p0y, p1x, p1y, p2x, p2y, t) {
688
+ const minX = Math.min(p0x, p1x, p2x);
689
+ const minY = Math.min(p0y, p1y, p2y);
690
+ const maxX = Math.max(p0x, p1x, p2x);
691
+ const maxY = Math.max(p0y, p1y, p2y);
692
+ let w00 = orient(p1x, p1y, p2x, p2y, minX, minY);
693
+ let w01 = orient(p2x, p2y, p0x, p0y, minX, minY);
694
+ let w02 = orient(p0x, p0y, p1x, p1y, minX, minY);
695
+ const a01 = p1y - p0y;
696
+ const b01 = p0x - p1x;
697
+ const a12 = p2y - p1y;
698
+ const b12 = p1x - p2x;
699
+ const a20 = p0y - p2y;
700
+ const b20 = p2x - p0x;
701
+ const a = orient(p0x, p0y, p1x, p1y, p2x, p2y);
702
+ const z0 = this.heightAt(p0x, p0y) / a;
703
+ const z1 = this.heightAt(p1x, p1y) / a;
704
+ const z2 = this.heightAt(p2x, p2y) / a;
705
+ let maxError = 0;
706
+ let mx = 0;
707
+ let my = 0;
708
+ let rms = 0;
709
+ for (let y = minY; y <= maxY; y++) {
710
+ let dx = 0;
711
+ if (w00 < 0 && a12 !== 0) {
712
+ dx = Math.max(dx, Math.floor(-w00 / a12));
713
+ }
714
+ if (w01 < 0 && a20 !== 0) {
715
+ dx = Math.max(dx, Math.floor(-w01 / a20));
716
+ }
717
+ if (w02 < 0 && a01 !== 0) {
718
+ dx = Math.max(dx, Math.floor(-w02 / a01));
719
+ }
720
+ let w0 = w00 + a12 * dx;
721
+ let w1 = w01 + a20 * dx;
722
+ let w2 = w02 + a01 * dx;
723
+ let wasInside = false;
724
+ for (let x = minX + dx; x <= maxX; x++) {
725
+ if (w0 >= 0 && w1 >= 0 && w2 >= 0) {
726
+ wasInside = true;
727
+ const z = z0 * w0 + z1 * w1 + z2 * w2;
728
+ const dz = Math.abs(z - this.heightAt(x, y));
729
+ rms += dz * dz;
730
+ if (dz > maxError) {
731
+ maxError = dz;
732
+ mx = x;
733
+ my = y;
734
+ }
735
+ } else if (wasInside) {
736
+ break;
737
+ }
738
+ w0 += a12;
739
+ w1 += a20;
740
+ w2 += a01;
741
+ }
742
+ w00 += b12;
743
+ w01 += b20;
744
+ w02 += b01;
745
+ }
746
+ if (mx === p0x && my === p0y || mx === p1x && my === p1y || mx === p2x && my === p2y) {
747
+ maxError = 0;
748
+ }
749
+ this._candidates[2 * t] = mx;
750
+ this._candidates[2 * t + 1] = my;
751
+ this._rms[t] = rms;
752
+ this._queuePush(t, maxError, rms);
753
+ }
754
+ // process the next triangle in the queue, splitting it with a new point
755
+ _step() {
756
+ const t = this._queuePop();
757
+ const e0 = t * 3 + 0;
758
+ const e1 = t * 3 + 1;
759
+ const e2 = t * 3 + 2;
760
+ const p0 = this.triangles[e0];
761
+ const p1 = this.triangles[e1];
762
+ const p2 = this.triangles[e2];
763
+ const ax = this.coords[2 * p0];
764
+ const ay = this.coords[2 * p0 + 1];
765
+ const bx = this.coords[2 * p1];
766
+ const by = this.coords[2 * p1 + 1];
767
+ const cx = this.coords[2 * p2];
768
+ const cy = this.coords[2 * p2 + 1];
769
+ const px = this._candidates[2 * t];
770
+ const py = this._candidates[2 * t + 1];
771
+ const pn = this._addPoint(px, py);
772
+ if (orient(ax, ay, bx, by, px, py) === 0) {
773
+ this._handleCollinear(pn, e0);
774
+ } else if (orient(bx, by, cx, cy, px, py) === 0) {
775
+ this._handleCollinear(pn, e1);
776
+ } else if (orient(cx, cy, ax, ay, px, py) === 0) {
777
+ this._handleCollinear(pn, e2);
778
+ } else {
779
+ const h0 = this._halfedges[e0];
780
+ const h1 = this._halfedges[e1];
781
+ const h2 = this._halfedges[e2];
782
+ const t0 = this._addTriangle(p0, p1, pn, h0, -1, -1, e0);
783
+ const t1 = this._addTriangle(p1, p2, pn, h1, -1, t0 + 1);
784
+ const t2 = this._addTriangle(p2, p0, pn, h2, t0 + 2, t1 + 1);
785
+ this._legalize(t0);
786
+ this._legalize(t1);
787
+ this._legalize(t2);
788
+ }
789
+ }
790
+ // add coordinates for a new vertex
791
+ _addPoint(x, y) {
792
+ const i = this.coords.length >> 1;
793
+ this.coords.push(x, y);
794
+ return i;
795
+ }
796
+ // add or update a triangle in the mesh
797
+ _addTriangle(a, b, c, ab, bc, ca, e = this.triangles.length) {
798
+ const t = e / 3;
799
+ this.triangles[e + 0] = a;
800
+ this.triangles[e + 1] = b;
801
+ this.triangles[e + 2] = c;
802
+ this._halfedges[e + 0] = ab;
803
+ this._halfedges[e + 1] = bc;
804
+ this._halfedges[e + 2] = ca;
805
+ if (ab >= 0) {
806
+ this._halfedges[ab] = e + 0;
807
+ }
808
+ if (bc >= 0) {
809
+ this._halfedges[bc] = e + 1;
810
+ }
811
+ if (ca >= 0) {
812
+ this._halfedges[ca] = e + 2;
813
+ }
814
+ this._candidates[2 * t + 0] = 0;
815
+ this._candidates[2 * t + 1] = 0;
816
+ this._queueIndices[t] = -1;
817
+ this._rms[t] = 0;
818
+ this._pending[this._pendingLen++] = t;
819
+ return e;
820
+ }
821
+ _legalize(a) {
822
+ const b = this._halfedges[a];
823
+ if (b < 0) {
824
+ return;
825
+ }
826
+ const a0 = a - a % 3;
827
+ const b0 = b - b % 3;
828
+ const al = a0 + (a + 1) % 3;
829
+ const ar = a0 + (a + 2) % 3;
830
+ const bl = b0 + (b + 2) % 3;
831
+ const br = b0 + (b + 1) % 3;
832
+ const p0 = this.triangles[ar];
833
+ const pr = this.triangles[a];
834
+ const pl = this.triangles[al];
835
+ const p1 = this.triangles[bl];
836
+ const coords = this.coords;
837
+ if (!inCircle(coords[2 * p0], coords[2 * p0 + 1], coords[2 * pr], coords[2 * pr + 1], coords[2 * pl], coords[2 * pl + 1], coords[2 * p1], coords[2 * p1 + 1])) {
838
+ return;
839
+ }
840
+ const hal = this._halfedges[al];
841
+ const har = this._halfedges[ar];
842
+ const hbl = this._halfedges[bl];
843
+ const hbr = this._halfedges[br];
844
+ this._queueRemove(a0 / 3);
845
+ this._queueRemove(b0 / 3);
846
+ const t0 = this._addTriangle(p0, p1, pl, -1, hbl, hal, a0);
847
+ const t1 = this._addTriangle(p1, p0, pr, t0, har, hbr, b0);
848
+ this._legalize(t0 + 1);
849
+ this._legalize(t1 + 2);
850
+ }
851
+ // handle a case where new vertex is on the edge of a triangle
852
+ _handleCollinear(pn, a) {
853
+ const a0 = a - a % 3;
854
+ const al = a0 + (a + 1) % 3;
855
+ const ar = a0 + (a + 2) % 3;
856
+ const p0 = this.triangles[ar];
857
+ const pr = this.triangles[a];
858
+ const pl = this.triangles[al];
859
+ const hal = this._halfedges[al];
860
+ const har = this._halfedges[ar];
861
+ const b = this._halfedges[a];
862
+ if (b < 0) {
863
+ const t02 = this._addTriangle(pn, p0, pr, -1, har, -1, a0);
864
+ const t12 = this._addTriangle(p0, pn, pl, t02, -1, hal);
865
+ this._legalize(t02 + 1);
866
+ this._legalize(t12 + 2);
867
+ return;
868
+ }
869
+ const b0 = b - b % 3;
870
+ const bl = b0 + (b + 2) % 3;
871
+ const br = b0 + (b + 1) % 3;
872
+ const p1 = this.triangles[bl];
873
+ const hbl = this._halfedges[bl];
874
+ const hbr = this._halfedges[br];
875
+ this._queueRemove(b0 / 3);
876
+ const t0 = this._addTriangle(p0, pr, pn, har, -1, -1, a0);
877
+ const t1 = this._addTriangle(pr, p1, pn, hbr, -1, t0 + 1, b0);
878
+ const t2 = this._addTriangle(p1, pl, pn, hbl, -1, t1 + 1);
879
+ const t3 = this._addTriangle(pl, p0, pn, hal, t0 + 2, t2 + 1);
880
+ this._legalize(t0);
881
+ this._legalize(t1);
882
+ this._legalize(t2);
883
+ this._legalize(t3);
884
+ }
885
+ // priority queue methods
886
+ _queuePush(t, error, rms) {
887
+ const i = this._queue.length;
888
+ this._queueIndices[t] = i;
889
+ this._queue.push(t);
890
+ this._errors.push(error);
891
+ this._rmsSum += rms;
892
+ this._queueUp(i);
893
+ }
894
+ _queuePop() {
895
+ const n = this._queue.length - 1;
896
+ this._queueSwap(0, n);
897
+ this._queueDown(0, n);
898
+ return this._queuePopBack();
899
+ }
900
+ _queuePopBack() {
901
+ const t = this._queue.pop();
902
+ this._errors.pop();
903
+ this._rmsSum -= this._rms[t];
904
+ this._queueIndices[t] = -1;
905
+ return t;
906
+ }
907
+ _queueRemove(t) {
908
+ const i = this._queueIndices[t];
909
+ if (i < 0) {
910
+ const it = this._pending.indexOf(t);
911
+ if (it !== -1) {
912
+ this._pending[it] = this._pending[--this._pendingLen];
913
+ } else {
914
+ throw new Error("Broken triangulation (something went wrong).");
915
+ }
916
+ return;
917
+ }
918
+ const n = this._queue.length - 1;
919
+ if (n !== i) {
920
+ this._queueSwap(i, n);
921
+ if (!this._queueDown(i, n)) {
922
+ this._queueUp(i);
923
+ }
924
+ }
925
+ this._queuePopBack();
926
+ }
927
+ _queueLess(i, j) {
928
+ return this._errors[i] > this._errors[j];
929
+ }
930
+ _queueSwap(i, j) {
931
+ const pi = this._queue[i];
932
+ const pj = this._queue[j];
933
+ this._queue[i] = pj;
934
+ this._queue[j] = pi;
935
+ this._queueIndices[pi] = j;
936
+ this._queueIndices[pj] = i;
937
+ const e = this._errors[i];
938
+ this._errors[i] = this._errors[j];
939
+ this._errors[j] = e;
940
+ }
941
+ _queueUp(j0) {
942
+ let j = j0;
943
+ while (true) {
944
+ const i = j - 1 >> 1;
945
+ if (i === j || !this._queueLess(j, i)) {
946
+ break;
947
+ }
948
+ this._queueSwap(i, j);
949
+ j = i;
950
+ }
951
+ }
952
+ _queueDown(i0, n) {
953
+ let i = i0;
954
+ while (true) {
955
+ const j1 = 2 * i + 1;
956
+ if (j1 >= n || j1 < 0) {
957
+ break;
958
+ }
959
+ const j2 = j1 + 1;
960
+ let j = j1;
961
+ if (j2 < n && this._queueLess(j2, j1)) {
962
+ j = j2;
963
+ }
964
+ if (!this._queueLess(j, i)) {
965
+ break;
966
+ }
967
+ this._queueSwap(i, j);
968
+ i = j;
969
+ }
970
+ return i > i0;
971
+ }
972
+ };
973
+ function orient(ax, ay, bx, by, cx, cy) {
974
+ return (bx - cx) * (ay - cy) - (by - cy) * (ax - cx);
975
+ }
976
+ function inCircle(ax, ay, bx, by, cx, cy, px, py) {
977
+ const dx = ax - px;
978
+ const dy = ay - py;
979
+ const ex = bx - px;
980
+ const ey = by - py;
981
+ const fx = cx - px;
982
+ const fy = cy - py;
983
+ const ap = dx * dx + dy * dy;
984
+ const bp = ex * ex + ey * ey;
985
+ const cp = fx * fx + fy * fy;
986
+ return dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + ap * (ex * fy - ey * fx) < 0;
987
+ }
988
+
989
+ // src/lib/parse-terrain.ts
990
+ function makeTerrainMeshFromImage(terrainImage, terrainOptions) {
991
+ const {
992
+ meshMaxError,
993
+ bounds,
994
+ elevationDecoder
995
+ } = terrainOptions;
996
+ const {
997
+ data,
998
+ width,
999
+ height
1000
+ } = terrainImage;
1001
+ let terrain;
1002
+ let mesh;
1003
+ switch (terrainOptions.tesselator) {
1004
+ case "martini":
1005
+ terrain = getTerrain(data, width, height, elevationDecoder, terrainOptions.tesselator);
1006
+ mesh = getMartiniTileMesh(meshMaxError, width, terrain);
1007
+ break;
1008
+ case "delatin":
1009
+ terrain = getTerrain(data, width, height, elevationDecoder, terrainOptions.tesselator);
1010
+ mesh = getDelatinTileMesh(meshMaxError, width, height, terrain);
1011
+ break;
1012
+ default:
1013
+ if (width === height && !(height & width - 1)) {
1014
+ terrain = getTerrain(data, width, height, elevationDecoder, "martini");
1015
+ mesh = getMartiniTileMesh(meshMaxError, width, terrain);
1016
+ } else {
1017
+ terrain = getTerrain(data, width, height, elevationDecoder, "delatin");
1018
+ mesh = getDelatinTileMesh(meshMaxError, width, height, terrain);
1019
+ }
1020
+ break;
1021
+ }
1022
+ const {
1023
+ vertices
1024
+ } = mesh;
1025
+ let {
1026
+ triangles
1027
+ } = mesh;
1028
+ let attributes = getMeshAttributes2(vertices, terrain, width, height, bounds);
1029
+ const boundingBox = getMeshBoundingBox(attributes);
1030
+ if (terrainOptions.skirtHeight) {
1031
+ const {
1032
+ attributes: newAttributes,
1033
+ triangles: newTriangles
1034
+ } = addSkirt(attributes, triangles, terrainOptions.skirtHeight);
1035
+ attributes = newAttributes;
1036
+ triangles = newTriangles;
1037
+ }
1038
+ return {
1039
+ // Data return by this loader implementation
1040
+ loaderData: {
1041
+ header: {}
1042
+ },
1043
+ header: {
1044
+ vertexCount: triangles.length,
1045
+ boundingBox
1046
+ },
1047
+ mode: 4,
1048
+ // TRIANGLES
1049
+ indices: {
1050
+ value: Uint32Array.from(triangles),
1051
+ size: 1
1052
+ },
1053
+ attributes
1054
+ };
1055
+ }
1056
+ function getMartiniTileMesh(meshMaxError, width, terrain) {
1057
+ const gridSize = width + 1;
1058
+ const martini = new Martini(gridSize);
1059
+ const tile = martini.createTile(terrain);
1060
+ const {
1061
+ vertices,
1062
+ triangles
1063
+ } = tile.getMesh(meshMaxError);
1064
+ return {
1065
+ vertices,
1066
+ triangles
1067
+ };
1068
+ }
1069
+ function getDelatinTileMesh(meshMaxError, width, height, terrain) {
1070
+ const tin = new Delatin(terrain, width + 1, height + 1);
1071
+ tin.run(meshMaxError);
1072
+ const {
1073
+ coords,
1074
+ triangles
1075
+ } = tin;
1076
+ const vertices = coords;
1077
+ return {
1078
+ vertices,
1079
+ triangles
1080
+ };
1081
+ }
1082
+ function getTerrain(imageData, width, height, elevationDecoder, tesselator) {
1083
+ const {
1084
+ rScaler,
1085
+ bScaler,
1086
+ gScaler,
1087
+ offset
1088
+ } = elevationDecoder;
1089
+ const terrain = new Float32Array((width + 1) * (height + 1));
1090
+ for (let i = 0, y = 0; y < height; y++) {
1091
+ for (let x = 0; x < width; x++, i++) {
1092
+ const k = i * 4;
1093
+ const r = imageData[k + 0];
1094
+ const g = imageData[k + 1];
1095
+ const b = imageData[k + 2];
1096
+ terrain[i + y] = r * rScaler + g * gScaler + b * bScaler + offset;
1097
+ }
1098
+ }
1099
+ if (tesselator === "martini") {
1100
+ for (let i = (width + 1) * width, x = 0; x < width; x++, i++) {
1101
+ terrain[i] = terrain[i - width - 1];
1102
+ }
1103
+ for (let i = height, y = 0; y < height + 1; y++, i += height + 1) {
1104
+ terrain[i] = terrain[i - 1];
1105
+ }
1106
+ }
1107
+ return terrain;
1108
+ }
1109
+ function getMeshAttributes2(vertices, terrain, width, height, bounds) {
1110
+ const gridSize = width + 1;
1111
+ const numOfVerticies = vertices.length / 2;
1112
+ const positions = new Float32Array(numOfVerticies * 3);
1113
+ const texCoords = new Float32Array(numOfVerticies * 2);
1114
+ const [minX, minY, maxX, maxY] = bounds || [0, 0, width, height];
1115
+ const xScale = (maxX - minX) / width;
1116
+ const yScale = (maxY - minY) / height;
1117
+ for (let i = 0; i < numOfVerticies; i++) {
1118
+ const x = vertices[i * 2];
1119
+ const y = vertices[i * 2 + 1];
1120
+ const pixelIdx = y * gridSize + x;
1121
+ positions[3 * i + 0] = x * xScale + minX;
1122
+ positions[3 * i + 1] = -y * yScale + maxY;
1123
+ positions[3 * i + 2] = terrain[pixelIdx];
1124
+ texCoords[2 * i + 0] = x / width;
1125
+ texCoords[2 * i + 1] = y / height;
1126
+ }
1127
+ return {
1128
+ POSITION: {
1129
+ value: positions,
1130
+ size: 3
1131
+ },
1132
+ TEXCOORD_0: {
1133
+ value: texCoords,
1134
+ size: 2
1135
+ }
1136
+ // NORMAL: {}, - optional, but creates the high poly look with lighting
1137
+ };
1138
+ }
1139
+
1140
+ // src/lib/utils/version.ts
1141
+ var VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
1142
+
1143
+ // src/terrain-loader.ts
1144
+ var TerrainLoader = {
1145
+ name: "Terrain",
1146
+ id: "terrain",
1147
+ module: "terrain",
1148
+ version: VERSION,
1149
+ worker: true,
1150
+ extensions: ["png", "pngraw", "jpg", "jpeg", "gif", "webp", "bmp"],
1151
+ mimeTypes: ["image/png", "image/jpeg", "image/gif", "image/webp", "image/bmp"],
1152
+ options: {
1153
+ terrain: {
1154
+ tesselator: "auto",
1155
+ bounds: void 0,
1156
+ meshMaxError: 10,
1157
+ elevationDecoder: {
1158
+ rScaler: 1,
1159
+ gScaler: 0,
1160
+ bScaler: 0,
1161
+ offset: 0
1162
+ },
1163
+ skirtHeight: void 0
1164
+ }
1165
+ }
1166
+ };
1167
+
1168
+ // src/quantized-mesh-loader.ts
1169
+ var QuantizedMeshLoader = {
1170
+ name: "Quantized Mesh",
1171
+ id: "quantized-mesh",
1172
+ module: "terrain",
1173
+ version: VERSION,
1174
+ worker: true,
1175
+ extensions: ["terrain"],
1176
+ mimeTypes: ["application/vnd.quantized-mesh"],
1177
+ options: {
1178
+ "quantized-mesh": {
1179
+ bounds: [0, 0, 1, 1],
1180
+ skirtHeight: null
1181
+ }
1182
+ }
1183
+ };
1184
+
1185
+ // src/index.ts
1186
+ var TerrainLoader2 = {
1187
+ ...TerrainLoader,
1188
+ parse: parseTerrain
1189
+ };
1190
+ async function parseTerrain(arrayBuffer, options, context) {
1191
+ const loadImageOptions = {
1192
+ ...options,
1193
+ mimeType: "application/x.image",
1194
+ image: {
1195
+ ...options?.image,
1196
+ type: "data"
1197
+ }
1198
+ };
1199
+ const image = await parseFromContext(arrayBuffer, [], loadImageOptions, context);
1200
+ const terrainOptions = {
1201
+ ...TerrainLoader2.options.terrain,
1202
+ ...options?.terrain
1203
+ };
1204
+ return makeTerrainMeshFromImage(image, terrainOptions);
1205
+ }
1206
+ var QuantizedMeshLoader2 = {
1207
+ ...QuantizedMeshLoader,
1208
+ parseSync: (arrayBuffer, options) => parseQuantizedMesh(arrayBuffer, options?.["quantized-mesh"]),
1209
+ parse: async (arrayBuffer, options) => parseQuantizedMesh(arrayBuffer, options?.["quantized-mesh"])
1210
+ };
1211
+ return __toCommonJS(src_exports);
1212
+ })();
1213
+ return __exports__;
1214
+ });