Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@loaders.gl/terrain

Package Overview
Dependencies
Maintainers
9
Versions
270
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@loaders.gl/terrain - npm Package Compare versions

Comparing version 4.2.0-alpha.4 to 4.2.0-alpha.5

dist/dist.min.js

351

dist/dist.dev.js

@@ -5,10 +5,15 @@ (function webpackUniversalModuleDefinition(root, factory) {

else if (typeof define === 'function' && define.amd) define([], factory);
else if (typeof exports === 'object') exports['loader'] = factory();
else root['loader'] = factory();})(globalThis, function () {
else if (typeof exports === 'object') exports['loaders'] = factory();
else root['loaders'] = factory();})(globalThis, function () {
"use strict";
var __exports__ = (() => {
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {

@@ -26,7 +31,23 @@ for (var name in all)

};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
// external-global-plugin:@loaders.gl/core
var require_core = __commonJS({
"external-global-plugin:@loaders.gl/core"(exports, module) {
module.exports = globalThis.loaders;
}
});
// bundle.ts
var bundle_exports = {};
__export(bundle_exports, {
QuantizedMeshLoader: () => QuantizedMeshLoader2,

@@ -38,2 +59,3 @@ QuantizedMeshWorkerLoader: () => QuantizedMeshLoader,

});
__reExport(bundle_exports, __toESM(require_core(), 1));

@@ -50,3 +72,5 @@ // ../loader-utils/src/loader-types.ts

if (!TypedArrayConstructor) {
throw new Error('"concatenateTypedArrays" - incorrect quantity of arguments or arguments have incompatible data types');
throw new Error(
'"concatenateTypedArrays" - incorrect quantity of arguments or arguments have incompatible data types'
);
}

@@ -84,7 +108,23 @@ const sumLength = arrays.reduce((acc, value) => acc + value.length, 0);

}
return [[minX, minY, minZ], [maxX, maxY, maxZ]];
return [
[minX, minY, minZ],
[maxX, maxY, maxZ]
];
}
// src/lib/decode-quantized-mesh.ts
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]]);
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]
]);
function decodeZigZag(value) {

@@ -101,6 +141,3 @@ return value >> 1 ^ -(value & 1);

}
return {
header,
headerEndPosition: position
};
return { header, headerEndPosition: position };
}

@@ -124,3 +161,5 @@ function decodeVertexData(dataView, headerEndPosition) {

v += decodeZigZag(dataView.getUint16(vArrayStartPosition + bytesPerArrayElement * i, true));
height += decodeZigZag(dataView.getUint16(heightArrayStartPosition + bytesPerArrayElement * i, true));
height += decodeZigZag(
dataView.getUint16(heightArrayStartPosition + bytesPerArrayElement * i, true)
);
vertexData[i] = u;

@@ -131,6 +170,3 @@ vertexData[i + vertexCount] = v;

position += elementArrayLength * 3;
return {
vertexData,
vertexDataEndPosition: position
};
return { vertexData, vertexDataEndPosition: position };
}

@@ -168,3 +204,8 @@ function decodeIndex(buffer, position, indicesCount, bytesPerIndex, encoded = true) {

const triangleIndicesCount = triangleCount * 3;
const triangleIndices = decodeIndex(dataView.buffer, position, triangleIndicesCount, bytesPerIndex);
const triangleIndices = decodeIndex(
dataView.buffer,
position,
triangleIndicesCount,
bytesPerIndex
);
position += triangleIndicesCount * bytesPerIndex;

@@ -187,3 +228,9 @@ return {

position += Uint32Array.BYTES_PER_ELEMENT;
const southIndices = decodeIndex(dataView.buffer, position, southVertexCount, bytesPerIndex, false);
const southIndices = decodeIndex(
dataView.buffer,
position,
southVertexCount,
bytesPerIndex,
false
);
position += southVertexCount * bytesPerIndex;

@@ -196,3 +243,9 @@ const eastVertexCount = dataView.getUint32(position, true);

position += Uint32Array.BYTES_PER_ELEMENT;
const northIndices = decodeIndex(dataView.buffer, position, northVertexCount, bytesPerIndex, false);
const northIndices = decodeIndex(
dataView.buffer,
position,
northVertexCount,
bytesPerIndex,
false
);
position += northVertexCount * bytesPerIndex;

@@ -208,6 +261,13 @@ return {

function decodeVertexNormalsExtension(extensionDataView) {
return new Uint8Array(extensionDataView.buffer, extensionDataView.byteOffset, extensionDataView.byteLength);
return new Uint8Array(
extensionDataView.buffer,
extensionDataView.byteOffset,
extensionDataView.byteLength
);
}
function decodeWaterMaskExtension(extensionDataView) {
return extensionDataView.buffer.slice(extensionDataView.byteOffset, extensionDataView.byteOffset + extensionDataView.byteLength);
return extensionDataView.buffer.slice(
extensionDataView.byteOffset,
extensionDataView.byteOffset + extensionDataView.byteLength
);
}

@@ -217,6 +277,3 @@ function decodeExtensions(dataView, indicesEndPosition) {

if (dataView.byteLength <= indicesEndPosition) {
return {
extensions,
extensionsEndPosition: indicesEndPosition
};
return { extensions, extensionsEndPosition: indicesEndPosition };
}

@@ -244,6 +301,3 @@ let position = indicesEndPosition;

}
return {
extensions,
extensionsEndPosition: position
};
return { extensions, extensionsEndPosition: position };
}

@@ -263,39 +317,19 @@ var DECODING_STEPS = {

const view = new DataView(data);
const {
header,
headerEndPosition
} = decodeHeader(view);
const { header, headerEndPosition } = decodeHeader(view);
if (options.maxDecodingStep < DECODING_STEPS.vertices) {
return {
header
};
return { header };
}
const {
const { vertexData, vertexDataEndPosition } = decodeVertexData(view, headerEndPosition);
if (options.maxDecodingStep < DECODING_STEPS.triangleIndices) {
return { header, vertexData };
}
const { triangleIndices, triangleIndicesEndPosition } = decodeTriangleIndices(
view,
vertexData,
vertexDataEndPosition
} = decodeVertexData(view, headerEndPosition);
if (options.maxDecodingStep < DECODING_STEPS.triangleIndices) {
return {
header,
vertexData
};
}
const {
triangleIndices,
triangleIndicesEndPosition
} = decodeTriangleIndices(view, vertexData, vertexDataEndPosition);
);
if (options.maxDecodingStep < DECODING_STEPS.edgeIndices) {
return {
header,
vertexData,
triangleIndices
};
return { header, vertexData, triangleIndices };
}
const {
westIndices,
southIndices,
eastIndices,
northIndices,
edgeIndicesEndPosition
} = decodeEdgeIndices(view, vertexData, triangleIndicesEndPosition);
const { westIndices, southIndices, eastIndices, northIndices, edgeIndicesEndPosition } = decodeEdgeIndices(view, vertexData, triangleIndicesEndPosition);
if (options.maxDecodingStep < DECODING_STEPS.extensions) {

@@ -312,5 +346,3 @@ return {

}
const {
extensions
} = decodeExtensions(view, edgeIndicesEndPosition);
const { extensions } = decodeExtensions(view, edgeIndicesEndPosition);
return {

@@ -400,8 +432,20 @@ header,

const vertex2Offset = edgeIndex * 2 + 1;
newPosition.set(attributes.POSITION.value.subarray(edge[0] * 3, edge[0] * 3 + 3), vertex1Offset * 3);
newPosition.set(
attributes.POSITION.value.subarray(edge[0] * 3, edge[0] * 3 + 3),
vertex1Offset * 3
);
newPosition[vertex1Offset * 3 + 2] = newPosition[vertex1Offset * 3 + 2] - skirtHeight;
newPosition.set(attributes.POSITION.value.subarray(edge[1] * 3, edge[1] * 3 + 3), vertex2Offset * 3);
newPosition.set(
attributes.POSITION.value.subarray(edge[1] * 3, edge[1] * 3 + 3),
vertex2Offset * 3
);
newPosition[vertex2Offset * 3 + 2] = newPosition[vertex2Offset * 3 + 2] - skirtHeight;
newTexcoord0.set(attributes.TEXCOORD_0.value.subarray(edge[0] * 2, edge[0] * 2 + 2), vertex1Offset * 2);
newTexcoord0.set(attributes.TEXCOORD_0.value.subarray(edge[1] * 2, edge[1] * 2 + 2), vertex2Offset * 2);
newTexcoord0.set(
attributes.TEXCOORD_0.value.subarray(edge[0] * 2, edge[0] * 2 + 2),
vertex1Offset * 2
);
newTexcoord0.set(
attributes.TEXCOORD_0.value.subarray(edge[1] * 2, edge[1] * 2 + 2),
vertex2Offset * 2
);
const triangle1Offset = edgeIndex * 2 * 3;

@@ -418,6 +462,4 @@ newTriangles[triangle1Offset] = edge[0];

function parseQuantizedMesh(arrayBuffer, options = {}) {
const { bounds } = options;
const {
bounds
} = options;
const {
header,

@@ -435,11 +477,13 @@ vertexData,

if (options?.skirtHeight) {
const {
attributes: newAttributes,
triangles: newTriangles
} = addSkirt(attributes, triangleIndices, options.skirtHeight, {
westIndices,
northIndices,
eastIndices,
southIndices
});
const { attributes: newAttributes, triangles: newTriangles } = addSkirt(
attributes,
triangleIndices,
options.skirtHeight,
{
westIndices,
northIndices,
eastIndices,
southIndices
}
);
attributes = newAttributes;

@@ -449,2 +493,3 @@ triangleIndices = newTriangles;

return {
// Data return by this loader implementation
loaderData: {

@@ -454,12 +499,12 @@ header: {}

header: {
// @ts-ignore
vertexCount: triangleIndices.length,
boundingBox
},
// TODO
schema: void 0,
topology: "triangle-list",
mode: 4,
indices: {
value: triangleIndices,
size: 1
},
// TRIANGLES
indices: { value: triangleIndices, size: 1 },
attributes

@@ -469,6 +514,3 @@ };

function getMeshAttributes(vertexData, header, bounds) {
const {
minHeight,
maxHeight
} = header;
const { minHeight, maxHeight } = header;
const [minX, minY, maxX, maxY] = bounds || [0, 0, 1, 1];

@@ -492,10 +534,6 @@ const xScale = maxX - minX;

return {
POSITION: {
value: positions,
size: 3
},
TEXCOORD_0: {
value: texCoords,
size: 2
}
POSITION: { value: positions, size: 3 },
TEXCOORD_0: { value: texCoords, size: 2 }
// TODO: Parse normals if they exist in the file
// NORMAL: {}, - optional, but creates the high poly look with lighting
};

@@ -668,2 +706,3 @@ }

}
// refine the mesh until its maximum error gets below the given one
run(maxError = 1) {

@@ -674,2 +713,3 @@ while (this.getMaxError() > maxError) {

}
// refine the mesh with a single point
refine() {

@@ -679,11 +719,15 @@ this._step();

}
// max error of the current mesh
getMaxError() {
return this._errors[0];
}
// root-mean-square deviation of the current mesh
getRMSD() {
return this._rmsSum > 0 ? Math.sqrt(this._rmsSum / (this.width * this.height)) : 0;
}
// height value at a given position
heightAt(x, y) {
return this.data[this.width * y + x];
}
// rasterize and queue all triangles that got added or updated in _step
_flush() {

@@ -696,6 +740,15 @@ const coords = this.coords;

const c = 2 * this.triangles[t * 3 + 2];
this._findCandidate(coords[a], coords[a + 1], coords[b], coords[b + 1], coords[c], coords[c + 1], t);
this._findCandidate(
coords[a],
coords[a + 1],
coords[b],
coords[b + 1],
coords[c],
coords[c + 1],
t
);
}
this._pendingLen = 0;
}
// rasterize a triangle, find its max error, and queue it for processing
_findCandidate(p0x, p0y, p1x, p1y, p2x, p2y, t) {

@@ -768,2 +821,3 @@ const minX = Math.min(p0x, p1x, p2x);

}
// process the next triangle in the queue, splitting it with a new point
_step() {

@@ -804,2 +858,3 @@ const t = this._queuePop();

}
// add coordinates for a new vertex
_addPoint(x, y) {

@@ -810,2 +865,3 @@ const i = this.coords.length >> 1;

}
// add or update a triangle in the mesh
_addTriangle(a, b, c, ab, bc, ca, e = this.triangles.length) {

@@ -851,3 +907,12 @@ const t = e / 3;

const coords = this.coords;
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])) {
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]
)) {
return;

@@ -866,2 +931,3 @@ }

}
// handle a case where new vertex is on the edge of a triangle
_handleCollinear(pn, a) {

@@ -900,2 +966,3 @@ const a0 = a - a % 3;

}
// priority queue methods
_queuePush(t, error, rms) {

@@ -1006,12 +1073,4 @@ const i = this._queue.length;

function makeTerrainMeshFromImage(terrainImage, terrainOptions) {
const {
meshMaxError,
bounds,
elevationDecoder
} = terrainOptions;
const {
data,
width,
height
} = terrainImage;
const { meshMaxError, bounds, elevationDecoder } = terrainOptions;
const { data, width, height } = terrainImage;
let terrain;

@@ -1038,15 +1097,12 @@ let mesh;

}
const {
vertices
} = mesh;
let {
triangles
} = mesh;
const { vertices } = mesh;
let { triangles } = mesh;
let attributes = getMeshAttributes2(vertices, terrain, width, height, bounds);
const boundingBox = getMeshBoundingBox(attributes);
if (terrainOptions.skirtHeight) {
const {
attributes: newAttributes,
triangles: newTriangles
} = addSkirt(attributes, triangles, terrainOptions.skirtHeight);
const { attributes: newAttributes, triangles: newTriangles } = addSkirt(
attributes,
triangles,
terrainOptions.skirtHeight
);
attributes = newAttributes;

@@ -1056,2 +1112,3 @@ triangles = newTriangles;

return {
// Data return by this loader implementation
loaderData: {

@@ -1065,6 +1122,4 @@ header: {}

mode: 4,
indices: {
value: Uint32Array.from(triangles),
size: 1
},
// TRIANGLES
indices: { value: Uint32Array.from(triangles), size: 1 },
attributes

@@ -1077,10 +1132,4 @@ };

const tile = martini.createTile(terrain);
const {
vertices,
triangles
} = tile.getMesh(meshMaxError);
return {
vertices,
triangles
};
const { vertices, triangles } = tile.getMesh(meshMaxError);
return { vertices, triangles };
}

@@ -1090,19 +1139,8 @@ function getDelatinTileMesh(meshMaxError, width, height, terrain) {

tin.run(meshMaxError);
const {
coords,
triangles
} = tin;
const { coords, triangles } = tin;
const vertices = coords;
return {
vertices,
triangles
};
return { vertices, triangles };
}
function getTerrain(imageData, width, height, elevationDecoder, tesselator) {
const {
rScaler,
bScaler,
gScaler,
offset
} = elevationDecoder;
const { rScaler, bScaler, gScaler, offset } = elevationDecoder;
const terrain = new Float32Array((width + 1) * (height + 1));

@@ -1147,10 +1185,5 @@ for (let i = 0, y = 0; y < height; y++) {

return {
POSITION: {
value: positions,
size: 3
},
TEXCOORD_0: {
value: texCoords,
size: 2
}
POSITION: { value: positions, size: 3 },
TEXCOORD_0: { value: texCoords, size: 2 }
// NORMAL: {}, - optional, but creates the high poly look with lighting
};

@@ -1160,3 +1193,3 @@ }

// src/lib/utils/version.ts
var VERSION = true ? "4.2.0-alpha.4" : "latest";
var VERSION = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";

@@ -1214,12 +1247,6 @@ // src/terrain-loader.ts

mimeType: "application/x.image",
image: {
...options?.image,
type: "data"
}
image: { ...options?.image, type: "data" }
};
const image = await parseFromContext(arrayBuffer, [], loadImageOptions, context);
const terrainOptions = {
...TerrainLoader2.options.terrain,
...options?.terrain
};
const terrainOptions = { ...TerrainLoader2.options.terrain, ...options?.terrain };
return makeTerrainMeshFromImage(image, terrainOptions);

@@ -1232,5 +1259,5 @@ }

};
return __toCommonJS(src_exports);
return __toCommonJS(bundle_exports);
})();
return __exports__;
});
import type { LoaderContext, LoaderWithParser } from '@loaders.gl/loader-utils';
import { TerrainLoader as TerrainWorkerLoader, TerrainLoaderOptions } from './terrain-loader';
import { QuantizedMeshLoader as QuantizedMeshWorkerLoader, QuantizedMeshLoaderOptions } from './quantized-mesh-loader';
import { TerrainLoader as TerrainWorkerLoader, TerrainLoaderOptions } from "./terrain-loader.js";
import { QuantizedMeshLoader as QuantizedMeshWorkerLoader, QuantizedMeshLoaderOptions } from "./quantized-mesh-loader.js";
export { TerrainWorkerLoader };

@@ -5,0 +5,0 @@ export declare const TerrainLoader: LoaderWithParser<any, never, TerrainLoaderOptions>;

@@ -0,1 +1,4 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { parseFromContext } from '@loaders.gl/loader-utils';

@@ -6,29 +9,29 @@ import { parseQuantizedMesh } from "./lib/parse-quantized-mesh.js";

import { QuantizedMeshLoader as QuantizedMeshWorkerLoader } from "./quantized-mesh-loader.js";
// TerrainLoader
export { TerrainWorkerLoader };
export const TerrainLoader = {
...TerrainWorkerLoader,
parse: parseTerrain
...TerrainWorkerLoader,
parse: parseTerrain
};
export async function parseTerrain(arrayBuffer, options, context) {
const loadImageOptions = {
...options,
mimeType: 'application/x.image',
image: {
...(options === null || options === void 0 ? void 0 : options.image),
type: 'data'
}
};
const image = await parseFromContext(arrayBuffer, [], loadImageOptions, context);
const terrainOptions = {
...TerrainLoader.options.terrain,
...(options === null || options === void 0 ? void 0 : options.terrain)
};
return makeTerrainMeshFromImage(image, terrainOptions);
const loadImageOptions = {
...options,
mimeType: 'application/x.image',
image: { ...options?.image, type: 'data' }
};
const image = await parseFromContext(arrayBuffer, [], loadImageOptions, context);
// Extend function to support additional mesh generation options (square grid or delatin)
const terrainOptions = { ...TerrainLoader.options.terrain, ...options?.terrain };
// @ts-expect-error sort out image typing asap
return makeTerrainMeshFromImage(image, terrainOptions);
}
// QuantizedMeshLoader
export { QuantizedMeshWorkerLoader };
/**
* Loader for quantized meshes
*/
export const QuantizedMeshLoader = {
...QuantizedMeshWorkerLoader,
parseSync: (arrayBuffer, options) => parseQuantizedMesh(arrayBuffer, options === null || options === void 0 ? void 0 : options['quantized-mesh']),
parse: async (arrayBuffer, options) => parseQuantizedMesh(arrayBuffer, options === null || options === void 0 ? void 0 : options['quantized-mesh'])
...QuantizedMeshWorkerLoader,
parseSync: (arrayBuffer, options) => parseQuantizedMesh(arrayBuffer, options?.['quantized-mesh']),
parse: async (arrayBuffer, options) => parseQuantizedMesh(arrayBuffer, options?.['quantized-mesh'])
};
//# sourceMappingURL=index.js.map

@@ -1,231 +0,226 @@

const QUANTIZED_MESH_HEADER = 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]]);
// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
// Copyright (C) 2018-2019 HERE Europe B.V.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
const QUANTIZED_MESH_HEADER = 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]
]);
function decodeZigZag(value) {
return value >> 1 ^ -(value & 1);
return (value >> 1) ^ -(value & 1);
}
function decodeHeader(dataView) {
let position = 0;
const header = {};
for (const [key, bytesCount] of QUANTIZED_MESH_HEADER) {
const getter = bytesCount === 8 ? dataView.getFloat64 : dataView.getFloat32;
header[key] = getter.call(dataView, position, true);
position += bytesCount;
}
return {
header,
headerEndPosition: position
};
let position = 0;
const header = {};
for (const [key, bytesCount] of QUANTIZED_MESH_HEADER) {
const getter = bytesCount === 8 ? dataView.getFloat64 : dataView.getFloat32;
header[key] = getter.call(dataView, position, true);
position += bytesCount;
}
return { header, headerEndPosition: position };
}
function decodeVertexData(dataView, headerEndPosition) {
let position = headerEndPosition;
const elementsPerVertex = 3;
const vertexCount = dataView.getUint32(position, true);
const vertexData = new Uint16Array(vertexCount * elementsPerVertex);
position += Uint32Array.BYTES_PER_ELEMENT;
const bytesPerArrayElement = Uint16Array.BYTES_PER_ELEMENT;
const elementArrayLength = vertexCount * bytesPerArrayElement;
const uArrayStartPosition = position;
const vArrayStartPosition = uArrayStartPosition + elementArrayLength;
const heightArrayStartPosition = vArrayStartPosition + elementArrayLength;
let u = 0;
let v = 0;
let height = 0;
for (let i = 0; i < vertexCount; i++) {
u += decodeZigZag(dataView.getUint16(uArrayStartPosition + bytesPerArrayElement * i, true));
v += decodeZigZag(dataView.getUint16(vArrayStartPosition + bytesPerArrayElement * i, true));
height += decodeZigZag(dataView.getUint16(heightArrayStartPosition + bytesPerArrayElement * i, true));
vertexData[i] = u;
vertexData[i + vertexCount] = v;
vertexData[i + vertexCount * 2] = height;
}
position += elementArrayLength * 3;
return {
vertexData,
vertexDataEndPosition: position
};
let position = headerEndPosition;
const elementsPerVertex = 3;
const vertexCount = dataView.getUint32(position, true);
const vertexData = new Uint16Array(vertexCount * elementsPerVertex);
position += Uint32Array.BYTES_PER_ELEMENT;
const bytesPerArrayElement = Uint16Array.BYTES_PER_ELEMENT;
const elementArrayLength = vertexCount * bytesPerArrayElement;
const uArrayStartPosition = position;
const vArrayStartPosition = uArrayStartPosition + elementArrayLength;
const heightArrayStartPosition = vArrayStartPosition + elementArrayLength;
let u = 0;
let v = 0;
let height = 0;
for (let i = 0; i < vertexCount; i++) {
u += decodeZigZag(dataView.getUint16(uArrayStartPosition + bytesPerArrayElement * i, true));
v += decodeZigZag(dataView.getUint16(vArrayStartPosition + bytesPerArrayElement * i, true));
height += decodeZigZag(dataView.getUint16(heightArrayStartPosition + bytesPerArrayElement * i, true));
vertexData[i] = u;
vertexData[i + vertexCount] = v;
vertexData[i + vertexCount * 2] = height;
}
position += elementArrayLength * 3;
return { vertexData, vertexDataEndPosition: position };
}
function decodeIndex(buffer, position, indicesCount, bytesPerIndex) {
let encoded = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
let indices;
if (bytesPerIndex === 2) {
indices = new Uint16Array(buffer, position, indicesCount);
} else {
indices = new Uint32Array(buffer, position, indicesCount);
}
if (!encoded) {
function decodeIndex(buffer, position, indicesCount, bytesPerIndex, encoded = true) {
let indices;
if (bytesPerIndex === 2) {
indices = new Uint16Array(buffer, position, indicesCount);
}
else {
indices = new Uint32Array(buffer, position, indicesCount);
}
if (!encoded) {
return indices;
}
let highest = 0;
for (let i = 0; i < indices.length; ++i) {
const code = indices[i];
indices[i] = highest - code;
if (code === 0) {
++highest;
}
}
return indices;
}
let highest = 0;
for (let i = 0; i < indices.length; ++i) {
const code = indices[i];
indices[i] = highest - code;
if (code === 0) {
++highest;
}
}
return indices;
}
function decodeTriangleIndices(dataView, vertexData, vertexDataEndPosition) {
let position = vertexDataEndPosition;
const elementsPerVertex = 3;
const vertexCount = vertexData.length / elementsPerVertex;
const bytesPerIndex = vertexCount > 65536 ? Uint32Array.BYTES_PER_ELEMENT : Uint16Array.BYTES_PER_ELEMENT;
if (position % bytesPerIndex !== 0) {
position += bytesPerIndex - position % bytesPerIndex;
}
const triangleCount = dataView.getUint32(position, true);
position += Uint32Array.BYTES_PER_ELEMENT;
const triangleIndicesCount = triangleCount * 3;
const triangleIndices = decodeIndex(dataView.buffer, position, triangleIndicesCount, bytesPerIndex);
position += triangleIndicesCount * bytesPerIndex;
return {
triangleIndicesEndPosition: position,
triangleIndices
};
let position = vertexDataEndPosition;
const elementsPerVertex = 3;
const vertexCount = vertexData.length / elementsPerVertex;
const bytesPerIndex = vertexCount > 65536 ? Uint32Array.BYTES_PER_ELEMENT : Uint16Array.BYTES_PER_ELEMENT;
if (position % bytesPerIndex !== 0) {
position += bytesPerIndex - (position % bytesPerIndex);
}
const triangleCount = dataView.getUint32(position, true);
position += Uint32Array.BYTES_PER_ELEMENT;
const triangleIndicesCount = triangleCount * 3;
const triangleIndices = decodeIndex(dataView.buffer, position, triangleIndicesCount, bytesPerIndex);
position += triangleIndicesCount * bytesPerIndex;
return {
triangleIndicesEndPosition: position,
triangleIndices
};
}
function decodeEdgeIndices(dataView, vertexData, triangleIndicesEndPosition) {
let position = triangleIndicesEndPosition;
const elementsPerVertex = 3;
const vertexCount = vertexData.length / elementsPerVertex;
const bytesPerIndex = vertexCount > 65536 ? Uint32Array.BYTES_PER_ELEMENT : Uint16Array.BYTES_PER_ELEMENT;
const westVertexCount = dataView.getUint32(position, true);
position += Uint32Array.BYTES_PER_ELEMENT;
const westIndices = decodeIndex(dataView.buffer, position, westVertexCount, bytesPerIndex, false);
position += westVertexCount * bytesPerIndex;
const southVertexCount = dataView.getUint32(position, true);
position += Uint32Array.BYTES_PER_ELEMENT;
const southIndices = decodeIndex(dataView.buffer, position, southVertexCount, bytesPerIndex, false);
position += southVertexCount * bytesPerIndex;
const eastVertexCount = dataView.getUint32(position, true);
position += Uint32Array.BYTES_PER_ELEMENT;
const eastIndices = decodeIndex(dataView.buffer, position, eastVertexCount, bytesPerIndex, false);
position += eastVertexCount * bytesPerIndex;
const northVertexCount = dataView.getUint32(position, true);
position += Uint32Array.BYTES_PER_ELEMENT;
const northIndices = decodeIndex(dataView.buffer, position, northVertexCount, bytesPerIndex, false);
position += northVertexCount * bytesPerIndex;
return {
edgeIndicesEndPosition: position,
westIndices,
southIndices,
eastIndices,
northIndices
};
let position = triangleIndicesEndPosition;
const elementsPerVertex = 3;
const vertexCount = vertexData.length / elementsPerVertex;
const bytesPerIndex = vertexCount > 65536 ? Uint32Array.BYTES_PER_ELEMENT : Uint16Array.BYTES_PER_ELEMENT;
const westVertexCount = dataView.getUint32(position, true);
position += Uint32Array.BYTES_PER_ELEMENT;
const westIndices = decodeIndex(dataView.buffer, position, westVertexCount, bytesPerIndex, false);
position += westVertexCount * bytesPerIndex;
const southVertexCount = dataView.getUint32(position, true);
position += Uint32Array.BYTES_PER_ELEMENT;
const southIndices = decodeIndex(dataView.buffer, position, southVertexCount, bytesPerIndex, false);
position += southVertexCount * bytesPerIndex;
const eastVertexCount = dataView.getUint32(position, true);
position += Uint32Array.BYTES_PER_ELEMENT;
const eastIndices = decodeIndex(dataView.buffer, position, eastVertexCount, bytesPerIndex, false);
position += eastVertexCount * bytesPerIndex;
const northVertexCount = dataView.getUint32(position, true);
position += Uint32Array.BYTES_PER_ELEMENT;
const northIndices = decodeIndex(dataView.buffer, position, northVertexCount, bytesPerIndex, false);
position += northVertexCount * bytesPerIndex;
return {
edgeIndicesEndPosition: position,
westIndices,
southIndices,
eastIndices,
northIndices
};
}
function decodeVertexNormalsExtension(extensionDataView) {
return new Uint8Array(extensionDataView.buffer, extensionDataView.byteOffset, extensionDataView.byteLength);
return new Uint8Array(extensionDataView.buffer, extensionDataView.byteOffset, extensionDataView.byteLength);
}
function decodeWaterMaskExtension(extensionDataView) {
return extensionDataView.buffer.slice(extensionDataView.byteOffset, extensionDataView.byteOffset + extensionDataView.byteLength);
return extensionDataView.buffer.slice(extensionDataView.byteOffset, extensionDataView.byteOffset + extensionDataView.byteLength);
}
function decodeExtensions(dataView, indicesEndPosition) {
const extensions = {};
if (dataView.byteLength <= indicesEndPosition) {
return {
extensions,
extensionsEndPosition: indicesEndPosition
};
}
let position = indicesEndPosition;
while (position < dataView.byteLength) {
const extensionId = dataView.getUint8(position, true);
position += Uint8Array.BYTES_PER_ELEMENT;
const extensionLength = dataView.getUint32(position, true);
position += Uint32Array.BYTES_PER_ELEMENT;
const extensionView = new DataView(dataView.buffer, position, extensionLength);
switch (extensionId) {
case 1:
{
extensions.vertexNormals = decodeVertexNormalsExtension(extensionView);
break;
const extensions = {};
if (dataView.byteLength <= indicesEndPosition) {
return { extensions, extensionsEndPosition: indicesEndPosition };
}
let position = indicesEndPosition;
while (position < dataView.byteLength) {
const extensionId = dataView.getUint8(position, true);
position += Uint8Array.BYTES_PER_ELEMENT;
const extensionLength = dataView.getUint32(position, true);
position += Uint32Array.BYTES_PER_ELEMENT;
const extensionView = new DataView(dataView.buffer, position, extensionLength);
switch (extensionId) {
case 1: {
extensions.vertexNormals = decodeVertexNormalsExtension(extensionView);
break;
}
case 2: {
extensions.waterMask = decodeWaterMaskExtension(extensionView);
break;
}
default: {
// console.warn(`Unknown extension with id ${extensionId}`)
}
}
case 2:
{
extensions.waterMask = decodeWaterMaskExtension(extensionView);
break;
}
default:
{}
position += extensionLength;
}
position += extensionLength;
}
return {
extensions,
extensionsEndPosition: position
};
return { extensions, extensionsEndPosition: position };
}
export const DECODING_STEPS = {
header: 0,
vertices: 1,
triangleIndices: 2,
edgeIndices: 3,
extensions: 4
header: 0,
vertices: 1,
triangleIndices: 2,
edgeIndices: 3,
extensions: 4
};
const DEFAULT_OPTIONS = {
maxDecodingStep: DECODING_STEPS.extensions
maxDecodingStep: DECODING_STEPS.extensions
};
export default function decode(data, userOptions) {
const options = Object.assign({}, DEFAULT_OPTIONS, userOptions);
const view = new DataView(data);
const {
header,
headerEndPosition
} = decodeHeader(view);
if (options.maxDecodingStep < DECODING_STEPS.vertices) {
const options = Object.assign({}, DEFAULT_OPTIONS, userOptions);
const view = new DataView(data);
const { header, headerEndPosition } = decodeHeader(view);
if (options.maxDecodingStep < DECODING_STEPS.vertices) {
return { header };
}
const { vertexData, vertexDataEndPosition } = decodeVertexData(view, headerEndPosition);
if (options.maxDecodingStep < DECODING_STEPS.triangleIndices) {
return { header, vertexData };
}
const { triangleIndices, triangleIndicesEndPosition } = decodeTriangleIndices(view, vertexData, vertexDataEndPosition);
if (options.maxDecodingStep < DECODING_STEPS.edgeIndices) {
return { header, vertexData, triangleIndices };
}
const { westIndices, southIndices, eastIndices, northIndices, edgeIndicesEndPosition } = decodeEdgeIndices(view, vertexData, triangleIndicesEndPosition);
if (options.maxDecodingStep < DECODING_STEPS.extensions) {
return {
header,
vertexData,
triangleIndices,
westIndices,
northIndices,
eastIndices,
southIndices
};
}
const { extensions } = decodeExtensions(view, edgeIndicesEndPosition);
return {
header
header,
vertexData,
triangleIndices,
westIndices,
northIndices,
eastIndices,
southIndices,
extensions
};
}
const {
vertexData,
vertexDataEndPosition
} = decodeVertexData(view, headerEndPosition);
if (options.maxDecodingStep < DECODING_STEPS.triangleIndices) {
return {
header,
vertexData
};
}
const {
triangleIndices,
triangleIndicesEndPosition
} = decodeTriangleIndices(view, vertexData, vertexDataEndPosition);
if (options.maxDecodingStep < DECODING_STEPS.edgeIndices) {
return {
header,
vertexData,
triangleIndices
};
}
const {
westIndices,
southIndices,
eastIndices,
northIndices,
edgeIndicesEndPosition
} = decodeEdgeIndices(view, vertexData, triangleIndicesEndPosition);
if (options.maxDecodingStep < DECODING_STEPS.extensions) {
return {
header,
vertexData,
triangleIndices,
westIndices,
northIndices,
eastIndices,
southIndices
};
}
const {
extensions
} = decodeExtensions(view, edgeIndicesEndPosition);
return {
header,
vertexData,
triangleIndices,
westIndices,
northIndices,
eastIndices,
southIndices,
extensions
};
}
//# sourceMappingURL=decode-quantized-mesh.js.map

@@ -0,355 +1,408 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
// ISC License
// Copyright(c) 2019, Michael Fogleman, Vladimir Agafonkin
// @ts-nocheck
/* eslint-disable complexity, max-params, max-statements, max-depth, no-constant-condition */
export default class Delatin {
constructor(data, width) {
let height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : width;
this.data = data;
this.width = width;
this.height = height;
this.coords = [];
this.triangles = [];
this._halfedges = [];
this._candidates = [];
this._queueIndices = [];
this._queue = [];
this._errors = [];
this._rms = [];
this._pending = [];
this._pendingLen = 0;
this._rmsSum = 0;
const x1 = width - 1;
const y1 = height - 1;
const p0 = this._addPoint(0, 0);
const p1 = this._addPoint(x1, 0);
const p2 = this._addPoint(0, y1);
const p3 = this._addPoint(x1, y1);
const t0 = this._addTriangle(p3, p0, p2, -1, -1, -1);
this._addTriangle(p0, p3, p1, t0, -1, -1);
this._flush();
}
run() {
let maxError = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
while (this.getMaxError() > maxError) {
this.refine();
constructor(data, width, height = width) {
this.data = data; // height data
this.width = width;
this.height = height;
this.coords = []; // vertex coordinates (x, y)
this.triangles = []; // mesh triangle indices
// additional triangle data
this._halfedges = [];
this._candidates = [];
this._queueIndices = [];
this._queue = []; // queue of added triangles
this._errors = [];
this._rms = [];
this._pending = []; // triangles pending addition to queue
this._pendingLen = 0;
this._rmsSum = 0;
const x1 = width - 1;
const y1 = height - 1;
const p0 = this._addPoint(0, 0);
const p1 = this._addPoint(x1, 0);
const p2 = this._addPoint(0, y1);
const p3 = this._addPoint(x1, y1);
// add initial two triangles
const t0 = this._addTriangle(p3, p0, p2, -1, -1, -1);
this._addTriangle(p0, p3, p1, t0, -1, -1);
this._flush();
}
}
refine() {
this._step();
this._flush();
}
getMaxError() {
return this._errors[0];
}
getRMSD() {
return this._rmsSum > 0 ? Math.sqrt(this._rmsSum / (this.width * this.height)) : 0;
}
heightAt(x, y) {
return this.data[this.width * y + x];
}
_flush() {
const coords = this.coords;
for (let i = 0; i < this._pendingLen; i++) {
const t = this._pending[i];
const a = 2 * this.triangles[t * 3 + 0];
const b = 2 * this.triangles[t * 3 + 1];
const c = 2 * this.triangles[t * 3 + 2];
this._findCandidate(coords[a], coords[a + 1], coords[b], coords[b + 1], coords[c], coords[c + 1], t);
}
this._pendingLen = 0;
}
_findCandidate(p0x, p0y, p1x, p1y, p2x, p2y, t) {
const minX = Math.min(p0x, p1x, p2x);
const minY = Math.min(p0y, p1y, p2y);
const maxX = Math.max(p0x, p1x, p2x);
const maxY = Math.max(p0y, p1y, p2y);
let w00 = orient(p1x, p1y, p2x, p2y, minX, minY);
let w01 = orient(p2x, p2y, p0x, p0y, minX, minY);
let w02 = orient(p0x, p0y, p1x, p1y, minX, minY);
const a01 = p1y - p0y;
const b01 = p0x - p1x;
const a12 = p2y - p1y;
const b12 = p1x - p2x;
const a20 = p0y - p2y;
const b20 = p2x - p0x;
const a = orient(p0x, p0y, p1x, p1y, p2x, p2y);
const z0 = this.heightAt(p0x, p0y) / a;
const z1 = this.heightAt(p1x, p1y) / a;
const z2 = this.heightAt(p2x, p2y) / a;
let maxError = 0;
let mx = 0;
let my = 0;
let rms = 0;
for (let y = minY; y <= maxY; y++) {
let dx = 0;
if (w00 < 0 && a12 !== 0) {
dx = Math.max(dx, Math.floor(-w00 / a12));
}
if (w01 < 0 && a20 !== 0) {
dx = Math.max(dx, Math.floor(-w01 / a20));
}
if (w02 < 0 && a01 !== 0) {
dx = Math.max(dx, Math.floor(-w02 / a01));
}
let w0 = w00 + a12 * dx;
let w1 = w01 + a20 * dx;
let w2 = w02 + a01 * dx;
let wasInside = false;
for (let x = minX + dx; x <= maxX; x++) {
if (w0 >= 0 && w1 >= 0 && w2 >= 0) {
wasInside = true;
const z = z0 * w0 + z1 * w1 + z2 * w2;
const dz = Math.abs(z - this.heightAt(x, y));
rms += dz * dz;
if (dz > maxError) {
maxError = dz;
mx = x;
my = y;
}
} else if (wasInside) {
break;
// refine the mesh until its maximum error gets below the given one
run(maxError = 1) {
while (this.getMaxError() > maxError) {
this.refine();
}
w0 += a12;
w1 += a20;
w2 += a01;
}
w00 += b12;
w01 += b20;
w02 += b01;
}
if (mx === p0x && my === p0y || mx === p1x && my === p1y || mx === p2x && my === p2y) {
maxError = 0;
// refine the mesh with a single point
refine() {
this._step();
this._flush();
}
this._candidates[2 * t] = mx;
this._candidates[2 * t + 1] = my;
this._rms[t] = rms;
this._queuePush(t, maxError, rms);
}
_step() {
const t = this._queuePop();
const e0 = t * 3 + 0;
const e1 = t * 3 + 1;
const e2 = t * 3 + 2;
const p0 = this.triangles[e0];
const p1 = this.triangles[e1];
const p2 = this.triangles[e2];
const ax = this.coords[2 * p0];
const ay = this.coords[2 * p0 + 1];
const bx = this.coords[2 * p1];
const by = this.coords[2 * p1 + 1];
const cx = this.coords[2 * p2];
const cy = this.coords[2 * p2 + 1];
const px = this._candidates[2 * t];
const py = this._candidates[2 * t + 1];
const pn = this._addPoint(px, py);
if (orient(ax, ay, bx, by, px, py) === 0) {
this._handleCollinear(pn, e0);
} else if (orient(bx, by, cx, cy, px, py) === 0) {
this._handleCollinear(pn, e1);
} else if (orient(cx, cy, ax, ay, px, py) === 0) {
this._handleCollinear(pn, e2);
} else {
const h0 = this._halfedges[e0];
const h1 = this._halfedges[e1];
const h2 = this._halfedges[e2];
const t0 = this._addTriangle(p0, p1, pn, h0, -1, -1, e0);
const t1 = this._addTriangle(p1, p2, pn, h1, -1, t0 + 1);
const t2 = this._addTriangle(p2, p0, pn, h2, t0 + 2, t1 + 1);
this._legalize(t0);
this._legalize(t1);
this._legalize(t2);
// max error of the current mesh
getMaxError() {
return this._errors[0];
}
}
_addPoint(x, y) {
const i = this.coords.length >> 1;
this.coords.push(x, y);
return i;
}
_addTriangle(a, b, c, ab, bc, ca) {
let e = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : this.triangles.length;
const t = e / 3;
this.triangles[e + 0] = a;
this.triangles[e + 1] = b;
this.triangles[e + 2] = c;
this._halfedges[e + 0] = ab;
this._halfedges[e + 1] = bc;
this._halfedges[e + 2] = ca;
if (ab >= 0) {
this._halfedges[ab] = e + 0;
// root-mean-square deviation of the current mesh
getRMSD() {
return this._rmsSum > 0 ? Math.sqrt(this._rmsSum / (this.width * this.height)) : 0;
}
if (bc >= 0) {
this._halfedges[bc] = e + 1;
// height value at a given position
heightAt(x, y) {
return this.data[this.width * y + x];
}
if (ca >= 0) {
this._halfedges[ca] = e + 2;
// rasterize and queue all triangles that got added or updated in _step
_flush() {
const coords = this.coords;
for (let i = 0; i < this._pendingLen; i++) {
const t = this._pending[i];
// rasterize triangle to find maximum pixel error
const a = 2 * this.triangles[t * 3 + 0];
const b = 2 * this.triangles[t * 3 + 1];
const c = 2 * this.triangles[t * 3 + 2];
this._findCandidate(coords[a], coords[a + 1], coords[b], coords[b + 1], coords[c], coords[c + 1], t);
}
this._pendingLen = 0;
}
this._candidates[2 * t + 0] = 0;
this._candidates[2 * t + 1] = 0;
this._queueIndices[t] = -1;
this._rms[t] = 0;
this._pending[this._pendingLen++] = t;
return e;
}
_legalize(a) {
const b = this._halfedges[a];
if (b < 0) {
return;
// rasterize a triangle, find its max error, and queue it for processing
_findCandidate(p0x, p0y, p1x, p1y, p2x, p2y, t) {
// triangle bounding box
const minX = Math.min(p0x, p1x, p2x);
const minY = Math.min(p0y, p1y, p2y);
const maxX = Math.max(p0x, p1x, p2x);
const maxY = Math.max(p0y, p1y, p2y);
// forward differencing variables
let w00 = orient(p1x, p1y, p2x, p2y, minX, minY);
let w01 = orient(p2x, p2y, p0x, p0y, minX, minY);
let w02 = orient(p0x, p0y, p1x, p1y, minX, minY);
const a01 = p1y - p0y;
const b01 = p0x - p1x;
const a12 = p2y - p1y;
const b12 = p1x - p2x;
const a20 = p0y - p2y;
const b20 = p2x - p0x;
// pre-multiplied z values at vertices
const a = orient(p0x, p0y, p1x, p1y, p2x, p2y);
const z0 = this.heightAt(p0x, p0y) / a;
const z1 = this.heightAt(p1x, p1y) / a;
const z2 = this.heightAt(p2x, p2y) / a;
// iterate over pixels in bounding box
let maxError = 0;
let mx = 0;
let my = 0;
let rms = 0;
for (let y = minY; y <= maxY; y++) {
// compute starting offset
let dx = 0;
if (w00 < 0 && a12 !== 0) {
dx = Math.max(dx, Math.floor(-w00 / a12));
}
if (w01 < 0 && a20 !== 0) {
dx = Math.max(dx, Math.floor(-w01 / a20));
}
if (w02 < 0 && a01 !== 0) {
dx = Math.max(dx, Math.floor(-w02 / a01));
}
let w0 = w00 + a12 * dx;
let w1 = w01 + a20 * dx;
let w2 = w02 + a01 * dx;
let wasInside = false;
for (let x = minX + dx; x <= maxX; x++) {
// check if inside triangle
if (w0 >= 0 && w1 >= 0 && w2 >= 0) {
wasInside = true;
// compute z using barycentric coordinates
const z = z0 * w0 + z1 * w1 + z2 * w2;
const dz = Math.abs(z - this.heightAt(x, y));
rms += dz * dz;
if (dz > maxError) {
maxError = dz;
mx = x;
my = y;
}
}
else if (wasInside) {
break;
}
w0 += a12;
w1 += a20;
w2 += a01;
}
w00 += b12;
w01 += b20;
w02 += b01;
}
if ((mx === p0x && my === p0y) || (mx === p1x && my === p1y) || (mx === p2x && my === p2y)) {
maxError = 0;
}
// update triangle metadata
this._candidates[2 * t] = mx;
this._candidates[2 * t + 1] = my;
this._rms[t] = rms;
// add triangle to priority queue
this._queuePush(t, maxError, rms);
}
const a0 = a - a % 3;
const b0 = b - b % 3;
const al = a0 + (a + 1) % 3;
const ar = a0 + (a + 2) % 3;
const bl = b0 + (b + 2) % 3;
const br = b0 + (b + 1) % 3;
const p0 = this.triangles[ar];
const pr = this.triangles[a];
const pl = this.triangles[al];
const p1 = this.triangles[bl];
const coords = this.coords;
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])) {
return;
// process the next triangle in the queue, splitting it with a new point
_step() {
// pop triangle with highest error from priority queue
const t = this._queuePop();
const e0 = t * 3 + 0;
const e1 = t * 3 + 1;
const e2 = t * 3 + 2;
const p0 = this.triangles[e0];
const p1 = this.triangles[e1];
const p2 = this.triangles[e2];
const ax = this.coords[2 * p0];
const ay = this.coords[2 * p0 + 1];
const bx = this.coords[2 * p1];
const by = this.coords[2 * p1 + 1];
const cx = this.coords[2 * p2];
const cy = this.coords[2 * p2 + 1];
const px = this._candidates[2 * t];
const py = this._candidates[2 * t + 1];
const pn = this._addPoint(px, py);
if (orient(ax, ay, bx, by, px, py) === 0) {
this._handleCollinear(pn, e0);
}
else if (orient(bx, by, cx, cy, px, py) === 0) {
this._handleCollinear(pn, e1);
}
else if (orient(cx, cy, ax, ay, px, py) === 0) {
this._handleCollinear(pn, e2);
}
else {
const h0 = this._halfedges[e0];
const h1 = this._halfedges[e1];
const h2 = this._halfedges[e2];
const t0 = this._addTriangle(p0, p1, pn, h0, -1, -1, e0);
const t1 = this._addTriangle(p1, p2, pn, h1, -1, t0 + 1);
const t2 = this._addTriangle(p2, p0, pn, h2, t0 + 2, t1 + 1);
this._legalize(t0);
this._legalize(t1);
this._legalize(t2);
}
}
const hal = this._halfedges[al];
const har = this._halfedges[ar];
const hbl = this._halfedges[bl];
const hbr = this._halfedges[br];
this._queueRemove(a0 / 3);
this._queueRemove(b0 / 3);
const t0 = this._addTriangle(p0, p1, pl, -1, hbl, hal, a0);
const t1 = this._addTriangle(p1, p0, pr, t0, har, hbr, b0);
this._legalize(t0 + 1);
this._legalize(t1 + 2);
}
_handleCollinear(pn, a) {
const a0 = a - a % 3;
const al = a0 + (a + 1) % 3;
const ar = a0 + (a + 2) % 3;
const p0 = this.triangles[ar];
const pr = this.triangles[a];
const pl = this.triangles[al];
const hal = this._halfedges[al];
const har = this._halfedges[ar];
const b = this._halfedges[a];
if (b < 0) {
const t0 = this._addTriangle(pn, p0, pr, -1, har, -1, a0);
const t1 = this._addTriangle(p0, pn, pl, t0, -1, hal);
this._legalize(t0 + 1);
this._legalize(t1 + 2);
return;
// add coordinates for a new vertex
_addPoint(x, y) {
const i = this.coords.length >> 1;
this.coords.push(x, y);
return i;
}
const b0 = b - b % 3;
const bl = b0 + (b + 2) % 3;
const br = b0 + (b + 1) % 3;
const p1 = this.triangles[bl];
const hbl = this._halfedges[bl];
const hbr = this._halfedges[br];
this._queueRemove(b0 / 3);
const t0 = this._addTriangle(p0, pr, pn, har, -1, -1, a0);
const t1 = this._addTriangle(pr, p1, pn, hbr, -1, t0 + 1, b0);
const t2 = this._addTriangle(p1, pl, pn, hbl, -1, t1 + 1);
const t3 = this._addTriangle(pl, p0, pn, hal, t0 + 2, t2 + 1);
this._legalize(t0);
this._legalize(t1);
this._legalize(t2);
this._legalize(t3);
}
_queuePush(t, error, rms) {
const i = this._queue.length;
this._queueIndices[t] = i;
this._queue.push(t);
this._errors.push(error);
this._rmsSum += rms;
this._queueUp(i);
}
_queuePop() {
const n = this._queue.length - 1;
this._queueSwap(0, n);
this._queueDown(0, n);
return this._queuePopBack();
}
_queuePopBack() {
const t = this._queue.pop();
this._errors.pop();
this._rmsSum -= this._rms[t];
this._queueIndices[t] = -1;
return t;
}
_queueRemove(t) {
const i = this._queueIndices[t];
if (i < 0) {
const it = this._pending.indexOf(t);
if (it !== -1) {
this._pending[it] = this._pending[--this._pendingLen];
} else {
throw new Error('Broken triangulation (something went wrong).');
}
return;
// add or update a triangle in the mesh
_addTriangle(a, b, c, ab, bc, ca, e = this.triangles.length) {
const t = e / 3; // new triangle index
// add triangle vertices
this.triangles[e + 0] = a;
this.triangles[e + 1] = b;
this.triangles[e + 2] = c;
// add triangle halfedges
this._halfedges[e + 0] = ab;
this._halfedges[e + 1] = bc;
this._halfedges[e + 2] = ca;
// link neighboring halfedges
if (ab >= 0) {
this._halfedges[ab] = e + 0;
}
if (bc >= 0) {
this._halfedges[bc] = e + 1;
}
if (ca >= 0) {
this._halfedges[ca] = e + 2;
}
// init triangle metadata
this._candidates[2 * t + 0] = 0;
this._candidates[2 * t + 1] = 0;
this._queueIndices[t] = -1;
this._rms[t] = 0;
// add triangle to pending queue for later rasterization
this._pending[this._pendingLen++] = t;
// return first halfedge index
return e;
}
const n = this._queue.length - 1;
if (n !== i) {
this._queueSwap(i, n);
if (!this._queueDown(i, n)) {
_legalize(a) {
// if the pair of triangles doesn't satisfy the Delaunay condition
// (p1 is inside the circumcircle of [p0, pl, pr]), flip them,
// then do the same check/flip recursively for the new pair of triangles
//
// pl pl
// /||\ / \
// al/ || \bl al/ \a
// / || \ / \
// / a||b \ flip /___ar___\
// p0\ || /p1 => p0\---bl---/p1
// \ || / \ /
// ar\ || /br b\ /br
// \||/ \ /
// pr pr
const b = this._halfedges[a];
if (b < 0) {
return;
}
const a0 = a - (a % 3);
const b0 = b - (b % 3);
const al = a0 + ((a + 1) % 3);
const ar = a0 + ((a + 2) % 3);
const bl = b0 + ((b + 2) % 3);
const br = b0 + ((b + 1) % 3);
const p0 = this.triangles[ar];
const pr = this.triangles[a];
const pl = this.triangles[al];
const p1 = this.triangles[bl];
const coords = this.coords;
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])) {
return;
}
const hal = this._halfedges[al];
const har = this._halfedges[ar];
const hbl = this._halfedges[bl];
const hbr = this._halfedges[br];
this._queueRemove(a0 / 3);
this._queueRemove(b0 / 3);
const t0 = this._addTriangle(p0, p1, pl, -1, hbl, hal, a0);
const t1 = this._addTriangle(p1, p0, pr, t0, har, hbr, b0);
this._legalize(t0 + 1);
this._legalize(t1 + 2);
}
// handle a case where new vertex is on the edge of a triangle
_handleCollinear(pn, a) {
const a0 = a - (a % 3);
const al = a0 + ((a + 1) % 3);
const ar = a0 + ((a + 2) % 3);
const p0 = this.triangles[ar];
const pr = this.triangles[a];
const pl = this.triangles[al];
const hal = this._halfedges[al];
const har = this._halfedges[ar];
const b = this._halfedges[a];
if (b < 0) {
const t0 = this._addTriangle(pn, p0, pr, -1, har, -1, a0);
const t1 = this._addTriangle(p0, pn, pl, t0, -1, hal);
this._legalize(t0 + 1);
this._legalize(t1 + 2);
return;
}
const b0 = b - (b % 3);
const bl = b0 + ((b + 2) % 3);
const br = b0 + ((b + 1) % 3);
const p1 = this.triangles[bl];
const hbl = this._halfedges[bl];
const hbr = this._halfedges[br];
this._queueRemove(b0 / 3);
const t0 = this._addTriangle(p0, pr, pn, har, -1, -1, a0);
const t1 = this._addTriangle(pr, p1, pn, hbr, -1, t0 + 1, b0);
const t2 = this._addTriangle(p1, pl, pn, hbl, -1, t1 + 1);
const t3 = this._addTriangle(pl, p0, pn, hal, t0 + 2, t2 + 1);
this._legalize(t0);
this._legalize(t1);
this._legalize(t2);
this._legalize(t3);
}
// priority queue methods
_queuePush(t, error, rms) {
const i = this._queue.length;
this._queueIndices[t] = i;
this._queue.push(t);
this._errors.push(error);
this._rmsSum += rms;
this._queueUp(i);
}
}
this._queuePopBack();
}
_queueLess(i, j) {
return this._errors[i] > this._errors[j];
}
_queueSwap(i, j) {
const pi = this._queue[i];
const pj = this._queue[j];
this._queue[i] = pj;
this._queue[j] = pi;
this._queueIndices[pi] = j;
this._queueIndices[pj] = i;
const e = this._errors[i];
this._errors[i] = this._errors[j];
this._errors[j] = e;
}
_queueUp(j0) {
let j = j0;
while (true) {
const i = j - 1 >> 1;
if (i === j || !this._queueLess(j, i)) {
break;
}
this._queueSwap(i, j);
j = i;
_queuePop() {
const n = this._queue.length - 1;
this._queueSwap(0, n);
this._queueDown(0, n);
return this._queuePopBack();
}
}
_queueDown(i0, n) {
let i = i0;
while (true) {
const j1 = 2 * i + 1;
if (j1 >= n || j1 < 0) {
break;
}
const j2 = j1 + 1;
let j = j1;
if (j2 < n && this._queueLess(j2, j1)) {
j = j2;
}
if (!this._queueLess(j, i)) {
break;
}
this._queueSwap(i, j);
i = j;
_queuePopBack() {
const t = this._queue.pop();
this._errors.pop();
this._rmsSum -= this._rms[t];
this._queueIndices[t] = -1;
return t;
}
return i > i0;
}
_queueRemove(t) {
const i = this._queueIndices[t];
if (i < 0) {
const it = this._pending.indexOf(t);
if (it !== -1) {
this._pending[it] = this._pending[--this._pendingLen];
}
else {
throw new Error('Broken triangulation (something went wrong).');
}
return;
}
const n = this._queue.length - 1;
if (n !== i) {
this._queueSwap(i, n);
if (!this._queueDown(i, n)) {
this._queueUp(i);
}
}
this._queuePopBack();
}
_queueLess(i, j) {
return this._errors[i] > this._errors[j];
}
_queueSwap(i, j) {
const pi = this._queue[i];
const pj = this._queue[j];
this._queue[i] = pj;
this._queue[j] = pi;
this._queueIndices[pi] = j;
this._queueIndices[pj] = i;
const e = this._errors[i];
this._errors[i] = this._errors[j];
this._errors[j] = e;
}
_queueUp(j0) {
let j = j0;
while (true) {
const i = (j - 1) >> 1;
if (i === j || !this._queueLess(j, i)) {
break;
}
this._queueSwap(i, j);
j = i;
}
}
_queueDown(i0, n) {
let i = i0;
while (true) {
const j1 = 2 * i + 1;
if (j1 >= n || j1 < 0) {
break;
}
const j2 = j1 + 1;
let j = j1;
if (j2 < n && this._queueLess(j2, j1)) {
j = j2;
}
if (!this._queueLess(j, i)) {
break;
}
this._queueSwap(i, j);
i = j;
}
return i > i0;
}
}
function orient(ax, ay, bx, by, cx, cy) {
return (bx - cx) * (ay - cy) - (by - cy) * (ax - cx);
return (bx - cx) * (ay - cy) - (by - cy) * (ax - cx);
}
function inCircle(ax, ay, bx, by, cx, cy, px, py) {
const dx = ax - px;
const dy = ay - py;
const ex = bx - px;
const ey = by - py;
const fx = cx - px;
const fy = cy - py;
const ap = dx * dx + dy * dy;
const bp = ex * ex + ey * ey;
const cp = fx * fx + fy * fy;
return dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + ap * (ex * fy - ey * fx) < 0;
const dx = ax - px;
const dy = ay - py;
const ex = bx - px;
const ey = by - py;
const fx = cx - px;
const fy = cy - py;
const ap = dx * dx + dy * dy;
const bp = ex * ex + ey * ey;
const cp = fx * fx + fy * fy;
return dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + ap * (ex * fy - ey * fx) < 0;
}
//# sourceMappingURL=index.js.map

@@ -0,89 +1,126 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { concatenateTypedArrays } from '@loaders.gl/loader-utils';
/**
* Add skirt to existing mesh
* @param {object} attributes - POSITION and TEXCOOD_0 attributes data
* @param {any} triangles - indices array of the mesh geometry
* @param skirtHeight - height of the skirt geometry
* @param outsideIndices - edge indices from quantized mesh data
* @returns - geometry data with added skirt
*/
export function addSkirt(attributes, triangles, skirtHeight, outsideIndices) {
const outsideEdges = outsideIndices ? getOutsideEdgesFromIndices(outsideIndices, attributes.POSITION.value) : getOutsideEdgesFromTriangles(triangles);
const newPosition = new attributes.POSITION.value.constructor(outsideEdges.length * 6);
const newTexcoord0 = new attributes.TEXCOORD_0.value.constructor(outsideEdges.length * 4);
const newTriangles = new triangles.constructor(outsideEdges.length * 6);
for (let i = 0; i < outsideEdges.length; i++) {
const edge = outsideEdges[i];
updateAttributesForNewEdge({
edge,
edgeIndex: i,
attributes,
skirtHeight,
newPosition,
newTexcoord0,
newTriangles
});
}
attributes.POSITION.value = concatenateTypedArrays(attributes.POSITION.value, newPosition);
attributes.TEXCOORD_0.value = concatenateTypedArrays(attributes.TEXCOORD_0.value, newTexcoord0);
const resultTriangles = triangles instanceof Array ? triangles.concat(newTriangles) : concatenateTypedArrays(triangles, newTriangles);
return {
attributes,
triangles: resultTriangles
};
const outsideEdges = outsideIndices
? getOutsideEdgesFromIndices(outsideIndices, attributes.POSITION.value)
: getOutsideEdgesFromTriangles(triangles);
// 2 new vertices for each outside edge
const newPosition = new attributes.POSITION.value.constructor(outsideEdges.length * 6);
const newTexcoord0 = new attributes.TEXCOORD_0.value.constructor(outsideEdges.length * 4);
// 2 new triangles for each outside edge
const newTriangles = new triangles.constructor(outsideEdges.length * 6);
for (let i = 0; i < outsideEdges.length; i++) {
const edge = outsideEdges[i];
updateAttributesForNewEdge({
edge,
edgeIndex: i,
attributes,
skirtHeight,
newPosition,
newTexcoord0,
newTriangles
});
}
attributes.POSITION.value = concatenateTypedArrays(attributes.POSITION.value, newPosition);
attributes.TEXCOORD_0.value = concatenateTypedArrays(attributes.TEXCOORD_0.value, newTexcoord0);
const resultTriangles = triangles instanceof Array
? triangles.concat(newTriangles)
: concatenateTypedArrays(triangles, newTriangles);
return {
attributes,
triangles: resultTriangles
};
}
/**
* Get geometry edges that located on a border of the mesh
* @param {any} triangles - indices array of the mesh geometry
* @returns {number[][]} - outside edges data
*/
function getOutsideEdgesFromTriangles(triangles) {
const edges = [];
for (let i = 0; i < triangles.length; i += 3) {
edges.push([triangles[i], triangles[i + 1]]);
edges.push([triangles[i + 1], triangles[i + 2]]);
edges.push([triangles[i + 2], triangles[i]]);
}
edges.sort((a, b) => Math.min(...a) - Math.min(...b) || Math.max(...a) - Math.max(...b));
const outsideEdges = [];
let index = 0;
while (index < edges.length) {
var _edges, _edges2;
if (edges[index][0] === ((_edges = edges[index + 1]) === null || _edges === void 0 ? void 0 : _edges[1]) && edges[index][1] === ((_edges2 = edges[index + 1]) === null || _edges2 === void 0 ? void 0 : _edges2[0])) {
index += 2;
} else {
outsideEdges.push(edges[index]);
index++;
const edges = [];
for (let i = 0; i < triangles.length; i += 3) {
edges.push([triangles[i], triangles[i + 1]]);
edges.push([triangles[i + 1], triangles[i + 2]]);
edges.push([triangles[i + 2], triangles[i]]);
}
}
return outsideEdges;
edges.sort((a, b) => Math.min(...a) - Math.min(...b) || Math.max(...a) - Math.max(...b));
const outsideEdges = [];
let index = 0;
while (index < edges.length) {
if (edges[index][0] === edges[index + 1]?.[1] && edges[index][1] === edges[index + 1]?.[0]) {
index += 2;
}
else {
outsideEdges.push(edges[index]);
index++;
}
}
return outsideEdges;
}
/**
* Get geometry edges that located on a border of the mesh
* @param {object} indices - edge indices from quantized mesh data
* @param {TypedArray} position - position attribute geometry data
* @returns {number[][]} - outside edges data
*/
function getOutsideEdgesFromIndices(indices, position) {
indices.westIndices.sort((a, b) => position[3 * a + 1] - position[3 * b + 1]);
indices.eastIndices.sort((a, b) => position[3 * b + 1] - position[3 * a + 1]);
indices.southIndices.sort((a, b) => position[3 * b] - position[3 * a]);
indices.northIndices.sort((a, b) => position[3 * a] - position[3 * b]);
const edges = [];
for (const index in indices) {
const indexGroup = indices[index];
for (let i = 0; i < indexGroup.length - 1; i++) {
edges.push([indexGroup[i], indexGroup[i + 1]]);
// Sort skirt indices to create adjacent triangles
indices.westIndices.sort((a, b) => position[3 * a + 1] - position[3 * b + 1]);
// Reverse (b - a) to match triangle winding
indices.eastIndices.sort((a, b) => position[3 * b + 1] - position[3 * a + 1]);
indices.southIndices.sort((a, b) => position[3 * b] - position[3 * a]);
// Reverse (b - a) to match triangle winding
indices.northIndices.sort((a, b) => position[3 * a] - position[3 * b]);
const edges = [];
for (const index in indices) {
const indexGroup = indices[index];
for (let i = 0; i < indexGroup.length - 1; i++) {
edges.push([indexGroup[i], indexGroup[i + 1]]);
}
}
}
return edges;
return edges;
}
function updateAttributesForNewEdge(_ref) {
let {
edge,
edgeIndex,
attributes,
skirtHeight,
newPosition,
newTexcoord0,
newTriangles
} = _ref;
const positionsLength = attributes.POSITION.value.length;
const vertex1Offset = edgeIndex * 2;
const vertex2Offset = edgeIndex * 2 + 1;
newPosition.set(attributes.POSITION.value.subarray(edge[0] * 3, edge[0] * 3 + 3), vertex1Offset * 3);
newPosition[vertex1Offset * 3 + 2] = newPosition[vertex1Offset * 3 + 2] - skirtHeight;
newPosition.set(attributes.POSITION.value.subarray(edge[1] * 3, edge[1] * 3 + 3), vertex2Offset * 3);
newPosition[vertex2Offset * 3 + 2] = newPosition[vertex2Offset * 3 + 2] - skirtHeight;
newTexcoord0.set(attributes.TEXCOORD_0.value.subarray(edge[0] * 2, edge[0] * 2 + 2), vertex1Offset * 2);
newTexcoord0.set(attributes.TEXCOORD_0.value.subarray(edge[1] * 2, edge[1] * 2 + 2), vertex2Offset * 2);
const triangle1Offset = edgeIndex * 2 * 3;
newTriangles[triangle1Offset] = edge[0];
newTriangles[triangle1Offset + 1] = positionsLength / 3 + vertex2Offset;
newTriangles[triangle1Offset + 2] = edge[1];
newTriangles[triangle1Offset + 3] = positionsLength / 3 + vertex2Offset;
newTriangles[triangle1Offset + 4] = edge[0];
newTriangles[triangle1Offset + 5] = positionsLength / 3 + vertex1Offset;
/**
* Get geometry edges that located on a border of the mesh
* @param {object} args
* @param {number[]} args.edge - edge indices in geometry
* @param {number} args.edgeIndex - edge index in outsideEdges array
* @param {object} args.attributes - POSITION and TEXCOORD_0 attributes
* @param {number} args.skirtHeight - height of the skirt geometry
* @param {TypedArray} args.newPosition - POSITION array for skirt data
* @param {TypedArray} args.newTexcoord0 - TEXCOORD_0 array for skirt data
* @param {TypedArray | Array} args.newTriangles - trinagle indices array for skirt data
* @returns {void}
*/
function updateAttributesForNewEdge({ edge, edgeIndex, attributes, skirtHeight, newPosition, newTexcoord0, newTriangles }) {
const positionsLength = attributes.POSITION.value.length;
const vertex1Offset = edgeIndex * 2;
const vertex2Offset = edgeIndex * 2 + 1;
// Define POSITION for new 1st vertex
newPosition.set(attributes.POSITION.value.subarray(edge[0] * 3, edge[0] * 3 + 3), vertex1Offset * 3);
newPosition[vertex1Offset * 3 + 2] = newPosition[vertex1Offset * 3 + 2] - skirtHeight; // put down elevation on the skirt height
// Define POSITION for new 2nd vertex
newPosition.set(attributes.POSITION.value.subarray(edge[1] * 3, edge[1] * 3 + 3), vertex2Offset * 3);
newPosition[vertex2Offset * 3 + 2] = newPosition[vertex2Offset * 3 + 2] - skirtHeight; // put down elevation on the skirt height
// Use same TEXCOORDS for skirt vertices
newTexcoord0.set(attributes.TEXCOORD_0.value.subarray(edge[0] * 2, edge[0] * 2 + 2), vertex1Offset * 2);
newTexcoord0.set(attributes.TEXCOORD_0.value.subarray(edge[1] * 2, edge[1] * 2 + 2), vertex2Offset * 2);
// Define new triangles
const triangle1Offset = edgeIndex * 2 * 3;
newTriangles[triangle1Offset] = edge[0];
newTriangles[triangle1Offset + 1] = positionsLength / 3 + vertex2Offset;
newTriangles[triangle1Offset + 2] = edge[1];
newTriangles[triangle1Offset + 3] = positionsLength / 3 + vertex2Offset;
newTriangles[triangle1Offset + 4] = edge[0];
newTriangles[triangle1Offset + 5] = positionsLength / 3 + vertex1Offset;
}
//# sourceMappingURL=skirt.js.map

@@ -0,85 +1,73 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { getMeshBoundingBox } from '@loaders.gl/schema';
import decode, { DECODING_STEPS } from "./decode-quantized-mesh.js";
import { addSkirt } from "./helpers/skirt.js";
export function parseQuantizedMesh(arrayBuffer) {
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
const {
bounds
} = options;
const {
header,
vertexData,
triangleIndices: originalTriangleIndices,
westIndices,
northIndices,
eastIndices,
southIndices
} = decode(arrayBuffer, DECODING_STEPS.triangleIndices);
let triangleIndices = originalTriangleIndices;
let attributes = getMeshAttributes(vertexData, header, bounds);
const boundingBox = getMeshBoundingBox(attributes);
if (options !== null && options !== void 0 && options.skirtHeight) {
const {
attributes: newAttributes,
triangles: newTriangles
} = addSkirt(attributes, triangleIndices, options.skirtHeight, {
westIndices,
northIndices,
eastIndices,
southIndices
});
attributes = newAttributes;
triangleIndices = newTriangles;
}
return {
loaderData: {
header: {}
},
header: {
vertexCount: triangleIndices.length,
boundingBox
},
schema: undefined,
topology: 'triangle-list',
mode: 4,
indices: {
value: triangleIndices,
size: 1
},
attributes
};
export function parseQuantizedMesh(arrayBuffer, options = {}) {
const { bounds } = options;
// Don't parse edge indices or format extensions
const { header, vertexData, triangleIndices: originalTriangleIndices, westIndices, northIndices, eastIndices, southIndices } = decode(arrayBuffer, DECODING_STEPS.triangleIndices);
let triangleIndices = originalTriangleIndices;
let attributes = getMeshAttributes(vertexData, header, bounds);
// Compute bounding box before adding skirt so that z values are not skewed
// TODO: Find bounding box from header, instead of doing extra pass over
// vertices.
const boundingBox = getMeshBoundingBox(attributes);
if (options?.skirtHeight) {
const { attributes: newAttributes, triangles: newTriangles } = addSkirt(attributes, triangleIndices, options.skirtHeight, {
westIndices,
northIndices,
eastIndices,
southIndices
});
attributes = newAttributes;
triangleIndices = newTriangles;
}
return {
// Data return by this loader implementation
loaderData: {
header: {}
},
header: {
// @ts-ignore
vertexCount: triangleIndices.length,
boundingBox
},
// TODO
schema: undefined,
topology: 'triangle-list',
mode: 4, // TRIANGLES
indices: { value: triangleIndices, size: 1 },
attributes
};
}
function getMeshAttributes(vertexData, header, bounds) {
const {
minHeight,
maxHeight
} = header;
const [minX, minY, maxX, maxY] = bounds || [0, 0, 1, 1];
const xScale = maxX - minX;
const yScale = maxY - minY;
const zScale = maxHeight - minHeight;
const nCoords = vertexData.length / 3;
const positions = new Float32Array(nCoords * 3);
const texCoords = new Float32Array(nCoords * 2);
for (let i = 0; i < nCoords; i++) {
const x = vertexData[i] / 32767;
const y = vertexData[i + nCoords] / 32767;
const z = vertexData[i + nCoords * 2] / 32767;
positions[3 * i + 0] = x * xScale + minX;
positions[3 * i + 1] = y * yScale + minY;
positions[3 * i + 2] = z * zScale + minHeight;
texCoords[2 * i + 0] = x;
texCoords[2 * i + 1] = y;
}
return {
POSITION: {
value: positions,
size: 3
},
TEXCOORD_0: {
value: texCoords,
size: 2
const { minHeight, maxHeight } = header;
const [minX, minY, maxX, maxY] = bounds || [0, 0, 1, 1];
const xScale = maxX - minX;
const yScale = maxY - minY;
const zScale = maxHeight - minHeight;
const nCoords = vertexData.length / 3;
// vec3. x, y defined by bounds, z in meters
const positions = new Float32Array(nCoords * 3);
// vec2. 1 to 1 relationship with position. represents the uv on the texture image. 0,0 to 1,1.
const texCoords = new Float32Array(nCoords * 2);
// Data is not interleaved; all u, then all v, then all heights
for (let i = 0; i < nCoords; i++) {
const x = vertexData[i] / 32767;
const y = vertexData[i + nCoords] / 32767;
const z = vertexData[i + nCoords * 2] / 32767;
positions[3 * i + 0] = x * xScale + minX;
positions[3 * i + 1] = y * yScale + minY;
positions[3 * i + 2] = z * zScale + minHeight;
texCoords[2 * i + 0] = x;
texCoords[2 * i + 1] = y;
}
};
return {
POSITION: { value: positions, size: 3 },
TEXCOORD_0: { value: texCoords, size: 2 }
// TODO: Parse normals if they exist in the file
// NORMAL: {}, - optional, but creates the high poly look with lighting
};
}
//# sourceMappingURL=parse-quantized-mesh.js.map

@@ -0,1 +1,4 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { getMeshBoundingBox } from '@loaders.gl/schema';

@@ -5,148 +8,143 @@ import Martini from '@mapbox/martini';

import { addSkirt } from "./helpers/skirt.js";
/**
* Returns generated mesh object from image data
*
* @param terrainImage terrain image data
* @param terrainOptions terrain options
* @returns mesh object
*/
export function makeTerrainMeshFromImage(terrainImage, terrainOptions) {
const {
meshMaxError,
bounds,
elevationDecoder
} = terrainOptions;
const {
data,
width,
height
} = terrainImage;
let terrain;
let mesh;
switch (terrainOptions.tesselator) {
case 'martini':
terrain = getTerrain(data, width, height, elevationDecoder, terrainOptions.tesselator);
mesh = getMartiniTileMesh(meshMaxError, width, terrain);
break;
case 'delatin':
terrain = getTerrain(data, width, height, elevationDecoder, terrainOptions.tesselator);
mesh = getDelatinTileMesh(meshMaxError, width, height, terrain);
break;
default:
if (width === height && !(height & width - 1)) {
terrain = getTerrain(data, width, height, elevationDecoder, 'martini');
mesh = getMartiniTileMesh(meshMaxError, width, terrain);
} else {
terrain = getTerrain(data, width, height, elevationDecoder, 'delatin');
mesh = getDelatinTileMesh(meshMaxError, width, height, terrain);
}
break;
}
const {
vertices
} = mesh;
let {
triangles
} = mesh;
let attributes = getMeshAttributes(vertices, terrain, width, height, bounds);
const boundingBox = getMeshBoundingBox(attributes);
if (terrainOptions.skirtHeight) {
const {
attributes: newAttributes,
triangles: newTriangles
} = addSkirt(attributes, triangles, terrainOptions.skirtHeight);
attributes = newAttributes;
triangles = newTriangles;
}
return {
loaderData: {
header: {}
},
header: {
vertexCount: triangles.length,
boundingBox
},
mode: 4,
indices: {
value: Uint32Array.from(triangles),
size: 1
},
attributes
};
const { meshMaxError, bounds, elevationDecoder } = terrainOptions;
const { data, width, height } = terrainImage;
let terrain;
let mesh;
switch (terrainOptions.tesselator) {
case 'martini':
terrain = getTerrain(data, width, height, elevationDecoder, terrainOptions.tesselator);
mesh = getMartiniTileMesh(meshMaxError, width, terrain);
break;
case 'delatin':
terrain = getTerrain(data, width, height, elevationDecoder, terrainOptions.tesselator);
mesh = getDelatinTileMesh(meshMaxError, width, height, terrain);
break;
// auto
default:
if (width === height && !(height & (width - 1))) {
terrain = getTerrain(data, width, height, elevationDecoder, 'martini');
mesh = getMartiniTileMesh(meshMaxError, width, terrain);
}
else {
terrain = getTerrain(data, width, height, elevationDecoder, 'delatin');
mesh = getDelatinTileMesh(meshMaxError, width, height, terrain);
}
break;
}
const { vertices } = mesh;
let { triangles } = mesh;
let attributes = getMeshAttributes(vertices, terrain, width, height, bounds);
// Compute bounding box before adding skirt so that z values are not skewed
const boundingBox = getMeshBoundingBox(attributes);
if (terrainOptions.skirtHeight) {
const { attributes: newAttributes, triangles: newTriangles } = addSkirt(attributes, triangles, terrainOptions.skirtHeight);
attributes = newAttributes;
triangles = newTriangles;
}
return {
// Data return by this loader implementation
loaderData: {
header: {}
},
header: {
vertexCount: triangles.length,
boundingBox
},
mode: 4, // TRIANGLES
indices: { value: Uint32Array.from(triangles), size: 1 },
attributes
};
}
/**
* Get Martini generated vertices and triangles
*
* @param {number} meshMaxError threshold for simplifying mesh
* @param {number} width width of the input data
* @param {number[] | Float32Array} terrain elevation data
* @returns {{vertices: Uint16Array, triangles: Uint32Array}} vertices and triangles data
*/
function getMartiniTileMesh(meshMaxError, width, terrain) {
const gridSize = width + 1;
const martini = new Martini(gridSize);
const tile = martini.createTile(terrain);
const {
vertices,
triangles
} = tile.getMesh(meshMaxError);
return {
vertices,
triangles
};
const gridSize = width + 1;
const martini = new Martini(gridSize);
const tile = martini.createTile(terrain);
const { vertices, triangles } = tile.getMesh(meshMaxError);
return { vertices, triangles };
}
/**
* Get Delatin generated vertices and triangles
*
* @param {number} meshMaxError threshold for simplifying mesh
* @param {number} width width of the input data array
* @param {number} height height of the input data array
* @param {number[] | Float32Array} terrain elevation data
* @returns {{vertices: number[], triangles: number[]}} vertices and triangles data
*/
function getDelatinTileMesh(meshMaxError, width, height, terrain) {
const tin = new Delatin(terrain, width + 1, height + 1);
tin.run(meshMaxError);
const {
coords,
triangles
} = tin;
const vertices = coords;
return {
vertices,
triangles
};
const tin = new Delatin(terrain, width + 1, height + 1);
tin.run(meshMaxError);
// @ts-expect-error
const { coords, triangles } = tin;
const vertices = coords;
return { vertices, triangles };
}
function getTerrain(imageData, width, height, elevationDecoder, tesselator) {
const {
rScaler,
bScaler,
gScaler,
offset
} = elevationDecoder;
const terrain = new Float32Array((width + 1) * (height + 1));
for (let i = 0, y = 0; y < height; y++) {
for (let x = 0; x < width; x++, i++) {
const k = i * 4;
const r = imageData[k + 0];
const g = imageData[k + 1];
const b = imageData[k + 2];
terrain[i + y] = r * rScaler + g * gScaler + b * bScaler + offset;
const { rScaler, bScaler, gScaler, offset } = elevationDecoder;
// From Martini demo
// https://observablehq.com/@mourner/martin-real-time-rtin-terrain-mesh
const terrain = new Float32Array((width + 1) * (height + 1));
// decode terrain values
for (let i = 0, y = 0; y < height; y++) {
for (let x = 0; x < width; x++, i++) {
const k = i * 4;
const r = imageData[k + 0];
const g = imageData[k + 1];
const b = imageData[k + 2];
terrain[i + y] = r * rScaler + g * gScaler + b * bScaler + offset;
}
}
}
if (tesselator === 'martini') {
for (let i = (width + 1) * width, x = 0; x < width; x++, i++) {
terrain[i] = terrain[i - width - 1];
if (tesselator === 'martini') {
// backfill bottom border
for (let i = (width + 1) * width, x = 0; x < width; x++, i++) {
terrain[i] = terrain[i - width - 1];
}
// backfill right border
for (let i = height, y = 0; y < height + 1; y++, i += height + 1) {
terrain[i] = terrain[i - 1];
}
}
for (let i = height, y = 0; y < height + 1; y++, i += height + 1) {
terrain[i] = terrain[i - 1];
}
}
return terrain;
return terrain;
}
function getMeshAttributes(vertices, terrain, width, height, bounds) {
const gridSize = width + 1;
const numOfVerticies = vertices.length / 2;
const positions = new Float32Array(numOfVerticies * 3);
const texCoords = new Float32Array(numOfVerticies * 2);
const [minX, minY, maxX, maxY] = bounds || [0, 0, width, height];
const xScale = (maxX - minX) / width;
const yScale = (maxY - minY) / height;
for (let i = 0; i < numOfVerticies; i++) {
const x = vertices[i * 2];
const y = vertices[i * 2 + 1];
const pixelIdx = y * gridSize + x;
positions[3 * i + 0] = x * xScale + minX;
positions[3 * i + 1] = -y * yScale + maxY;
positions[3 * i + 2] = terrain[pixelIdx];
texCoords[2 * i + 0] = x / width;
texCoords[2 * i + 1] = y / height;
}
return {
POSITION: {
value: positions,
size: 3
},
TEXCOORD_0: {
value: texCoords,
size: 2
const gridSize = width + 1;
const numOfVerticies = vertices.length / 2;
// vec3. x, y in pixels, z in meters
const positions = new Float32Array(numOfVerticies * 3);
// vec2. 1 to 1 relationship with position. represents the uv on the texture image. 0,0 to 1,1.
const texCoords = new Float32Array(numOfVerticies * 2);
const [minX, minY, maxX, maxY] = bounds || [0, 0, width, height];
const xScale = (maxX - minX) / width;
const yScale = (maxY - minY) / height;
for (let i = 0; i < numOfVerticies; i++) {
const x = vertices[i * 2];
const y = vertices[i * 2 + 1];
const pixelIdx = y * gridSize + x;
positions[3 * i + 0] = x * xScale + minX;
positions[3 * i + 1] = -y * yScale + maxY;
positions[3 * i + 2] = terrain[pixelIdx];
texCoords[2 * i + 0] = x / width;
texCoords[2 * i + 1] = y / height;
}
};
return {
POSITION: { value: positions, size: 3 },
TEXCOORD_0: { value: texCoords, size: 2 }
// NORMAL: {}, - optional, but creates the high poly look with lighting
};
}
//# sourceMappingURL=parse-terrain.js.map

@@ -0,2 +1,7 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
// Version constant cannot be imported, it needs to correspond to the build version of **this** module.
// __VERSION__ is injected by babel-plugin-version-inline
// @ts-ignore TS2304: Cannot find name '__VERSION__'.
export const VERSION = typeof "4.2.0-alpha.4" !== 'undefined' ? "4.2.0-alpha.4" : 'latest';
//# sourceMappingURL=version.js.map

@@ -0,17 +1,22 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { VERSION } from "./lib/utils/version.js";
/**
* Worker loader for quantized meshes
*/
export const QuantizedMeshLoader = {
name: 'Quantized Mesh',
id: 'quantized-mesh',
module: 'terrain',
version: VERSION,
worker: true,
extensions: ['terrain'],
mimeTypes: ['application/vnd.quantized-mesh'],
options: {
'quantized-mesh': {
bounds: [0, 0, 1, 1],
skirtHeight: null
name: 'Quantized Mesh',
id: 'quantized-mesh',
module: 'terrain',
version: VERSION,
worker: true,
extensions: ['terrain'],
mimeTypes: ['application/vnd.quantized-mesh'],
options: {
'quantized-mesh': {
bounds: [0, 0, 1, 1],
skirtHeight: null
}
}
}
};
//# sourceMappingURL=quantized-mesh-loader.js.map
import type { Loader } from '@loaders.gl/loader-utils';
import type { ImageLoaderOptions } from '@loaders.gl/images';
import { TerrainOptions } from './lib/parse-terrain';
import { TerrainOptions } from "./lib/parse-terrain.js";
import { Mesh } from '@loaders.gl/schema';

@@ -5,0 +5,0 @@ export type TerrainLoaderOptions = ImageLoaderOptions & {

@@ -0,25 +1,30 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { VERSION } from "./lib/utils/version.js";
/**
* Worker loader for image encoded terrain
*/
export const TerrainLoader = {
name: 'Terrain',
id: 'terrain',
module: 'terrain',
version: VERSION,
worker: true,
extensions: ['png', 'pngraw', 'jpg', 'jpeg', 'gif', 'webp', 'bmp'],
mimeTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp'],
options: {
terrain: {
tesselator: 'auto',
bounds: undefined,
meshMaxError: 10,
elevationDecoder: {
rScaler: 1,
gScaler: 0,
bScaler: 0,
offset: 0
},
skirtHeight: undefined
name: 'Terrain',
id: 'terrain',
module: 'terrain',
version: VERSION,
worker: true,
extensions: ['png', 'pngraw', 'jpg', 'jpeg', 'gif', 'webp', 'bmp'],
mimeTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/bmp'],
options: {
terrain: {
tesselator: 'auto',
bounds: undefined,
meshMaxError: 10,
elevationDecoder: {
rScaler: 1,
gScaler: 0,
bScaler: 0,
offset: 0
},
skirtHeight: undefined
}
}
}
};
//# sourceMappingURL=terrain-loader.js.map

@@ -0,4 +1,6 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { createLoaderWorker } from '@loaders.gl/loader-utils';
import { QuantizedMeshLoader } from "../index.js";
createLoaderWorker(QuantizedMeshLoader);
//# sourceMappingURL=quantized-mesh-worker.js.map

@@ -0,4 +1,6 @@

// loaders.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import { createLoaderWorker } from '@loaders.gl/loader-utils';
import { TerrainLoader } from "../index.js";
createLoaderWorker(TerrainLoader);
//# sourceMappingURL=terrain-worker.js.map
{
"name": "@loaders.gl/terrain",
"version": "4.2.0-alpha.4",
"version": "4.2.0-alpha.5",
"description": "Framework-independent loader for terrain raster formats",

@@ -39,4 +39,5 @@ "license": "MIT",

"scripts": {
"pre-build": "npm run build-worker && npm run build-worker2 && npm run build-bundle && npm run build-bundle -- --env=dev",
"build-bundle": "ocular-bundle ./src/index.ts",
"pre-build": "npm run build-worker && npm run build-worker2 && npm run build-bundle && npm run build-bundle-dev",
"build-bundle": "ocular-bundle ./bundle.ts --output=dist/dist.min.js",
"build-bundle-dev": "ocular-bundle ./bundle.ts --env=dev --output=dist/dist.dev.js",
"build-worker": "esbuild src/workers/terrain-worker.ts --bundle --outfile=dist/terrain-worker.js --define:__VERSION__=\\\"$npm_package_version\\\"",

@@ -46,9 +47,11 @@ "build-worker2": "esbuild src/workers/quantized-mesh-worker.ts --bundle --outfile=dist/quantized-mesh-worker.js --define:__VERSION__=\\\"$npm_package_version\\\""

"dependencies": {
"@babel/runtime": "^7.3.1",
"@loaders.gl/images": "4.2.0-alpha.4",
"@loaders.gl/loader-utils": "4.2.0-alpha.4",
"@loaders.gl/schema": "4.2.0-alpha.4",
"@loaders.gl/images": "4.2.0-alpha.5",
"@loaders.gl/loader-utils": "4.2.0-alpha.5",
"@loaders.gl/schema": "4.2.0-alpha.5",
"@mapbox/martini": "^0.2.0"
},
"gitHead": "6c52dee5c3f005648a394cc4aee7fc37005c8e83"
"peerDependencies": {
"@loaders.gl/core": "^4.0.0"
},
"gitHead": "32d95a81971f104e4dfeb88ab57065f05321a76a"
}

@@ -7,3 +7,3 @@ // loaders.gl

import Martini from '@mapbox/martini';
import Delatin from './delatin';
import Delatin from './delatin/index';
import {addSkirt} from './helpers/skirt';

@@ -10,0 +10,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc