cesium
Version:
CesiumJS is a JavaScript library for creating 3D globes and 2D maps in a web browser without a plugin.
1,421 lines (1,256 loc) • 119 kB
JavaScript
/* This file is automatically rebuilt by the Cesium build process. */
define(['exports', './AttributeCompression-4d18cc04', './Matrix2-fc7e9822', './RuntimeError-c581ca93', './defaultValue-94c3e563', './ComponentDatatype-4a60b8d6', './Transforms-3ac41eb6', './EncodedCartesian3-d3e254ea', './GeometryAttribute-a441ff32', './IndexDatatype-db156785', './IntersectionTests-68fbc42d', './Plane-e20fba8c'], (function (exports, AttributeCompression, Matrix2, RuntimeError, defaultValue, ComponentDatatype, Transforms, EncodedCartesian3, GeometryAttribute, IndexDatatype, IntersectionTests, Plane) { 'use strict';
const scratchCartesian1 = new Matrix2.Cartesian3();
const scratchCartesian2$1 = new Matrix2.Cartesian3();
const scratchCartesian3$1 = new Matrix2.Cartesian3();
/**
* Computes the barycentric coordinates for a point with respect to a triangle.
*
* @function
*
* @param {Cartesian2|Cartesian3} point The point to test.
* @param {Cartesian2|Cartesian3} p0 The first point of the triangle, corresponding to the barycentric x-axis.
* @param {Cartesian2|Cartesian3} p1 The second point of the triangle, corresponding to the barycentric y-axis.
* @param {Cartesian2|Cartesian3} p2 The third point of the triangle, corresponding to the barycentric z-axis.
* @param {Cartesian3} [result] The object onto which to store the result.
* @returns {Cartesian3|undefined} The modified result parameter or a new Cartesian3 instance if one was not provided. If the triangle is degenerate the function will return undefined.
*
* @example
* // Returns Cartesian3.UNIT_X
* const p = new Cesium.Cartesian3(-1.0, 0.0, 0.0);
* const b = Cesium.barycentricCoordinates(p,
* new Cesium.Cartesian3(-1.0, 0.0, 0.0),
* new Cesium.Cartesian3( 1.0, 0.0, 0.0),
* new Cesium.Cartesian3( 0.0, 1.0, 1.0));
*/
function barycentricCoordinates(point, p0, p1, p2, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.defined("point", point);
RuntimeError.Check.defined("p0", p0);
RuntimeError.Check.defined("p1", p1);
RuntimeError.Check.defined("p2", p2);
//>>includeEnd('debug');
if (!defaultValue.defined(result)) {
result = new Matrix2.Cartesian3();
}
// Implementation based on http://www.blackpawn.com/texts/pointinpoly/default.html.
let v0;
let v1;
let v2;
let dot00;
let dot01;
let dot02;
let dot11;
let dot12;
if (!defaultValue.defined(p0.z)) {
if (Matrix2.Cartesian2.equalsEpsilon(point, p0, ComponentDatatype.CesiumMath.EPSILON14)) {
return Matrix2.Cartesian3.clone(Matrix2.Cartesian3.UNIT_X, result);
}
if (Matrix2.Cartesian2.equalsEpsilon(point, p1, ComponentDatatype.CesiumMath.EPSILON14)) {
return Matrix2.Cartesian3.clone(Matrix2.Cartesian3.UNIT_Y, result);
}
if (Matrix2.Cartesian2.equalsEpsilon(point, p2, ComponentDatatype.CesiumMath.EPSILON14)) {
return Matrix2.Cartesian3.clone(Matrix2.Cartesian3.UNIT_Z, result);
}
v0 = Matrix2.Cartesian2.subtract(p1, p0, scratchCartesian1);
v1 = Matrix2.Cartesian2.subtract(p2, p0, scratchCartesian2$1);
v2 = Matrix2.Cartesian2.subtract(point, p0, scratchCartesian3$1);
dot00 = Matrix2.Cartesian2.dot(v0, v0);
dot01 = Matrix2.Cartesian2.dot(v0, v1);
dot02 = Matrix2.Cartesian2.dot(v0, v2);
dot11 = Matrix2.Cartesian2.dot(v1, v1);
dot12 = Matrix2.Cartesian2.dot(v1, v2);
} else {
if (Matrix2.Cartesian3.equalsEpsilon(point, p0, ComponentDatatype.CesiumMath.EPSILON14)) {
return Matrix2.Cartesian3.clone(Matrix2.Cartesian3.UNIT_X, result);
}
if (Matrix2.Cartesian3.equalsEpsilon(point, p1, ComponentDatatype.CesiumMath.EPSILON14)) {
return Matrix2.Cartesian3.clone(Matrix2.Cartesian3.UNIT_Y, result);
}
if (Matrix2.Cartesian3.equalsEpsilon(point, p2, ComponentDatatype.CesiumMath.EPSILON14)) {
return Matrix2.Cartesian3.clone(Matrix2.Cartesian3.UNIT_Z, result);
}
v0 = Matrix2.Cartesian3.subtract(p1, p0, scratchCartesian1);
v1 = Matrix2.Cartesian3.subtract(p2, p0, scratchCartesian2$1);
v2 = Matrix2.Cartesian3.subtract(point, p0, scratchCartesian3$1);
dot00 = Matrix2.Cartesian3.dot(v0, v0);
dot01 = Matrix2.Cartesian3.dot(v0, v1);
dot02 = Matrix2.Cartesian3.dot(v0, v2);
dot11 = Matrix2.Cartesian3.dot(v1, v1);
dot12 = Matrix2.Cartesian3.dot(v1, v2);
}
result.y = dot11 * dot02 - dot01 * dot12;
result.z = dot00 * dot12 - dot01 * dot02;
const q = dot00 * dot11 - dot01 * dot01;
// Triangle is degenerate
if (q === 0) {
return undefined;
}
result.y /= q;
result.z /= q;
result.x = 1.0 - result.y - result.z;
return result;
}
/**
* Encapsulates an algorithm to optimize triangles for the post
* vertex-shader cache. This is based on the 2007 SIGGRAPH paper
* 'Fast Triangle Reordering for Vertex Locality and Reduced Overdraw.'
* The runtime is linear but several passes are made.
*
* @namespace Tipsify
*
* @see <a href='http://gfx.cs.princeton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf'>
* Fast Triangle Reordering for Vertex Locality and Reduced Overdraw</a>
* by Sander, Nehab, and Barczak
*
* @private
*/
const Tipsify = {};
/**
* Calculates the average cache miss ratio (ACMR) for a given set of indices.
*
* @param {Object} options Object with the following properties:
* @param {Number[]} options.indices Lists triads of numbers corresponding to the indices of the vertices
* in the vertex buffer that define the geometry's triangles.
* @param {Number} [options.maximumIndex] The maximum value of the elements in <code>args.indices</code>.
* If not supplied, this value will be computed.
* @param {Number} [options.cacheSize=24] The number of vertices that can be stored in the cache at any one time.
* @returns {Number} The average cache miss ratio (ACMR).
*
* @exception {DeveloperError} indices length must be a multiple of three.
* @exception {DeveloperError} cacheSize must be greater than two.
*
* @example
* const indices = [0, 1, 2, 3, 4, 5];
* const maxIndex = 5;
* const cacheSize = 3;
* const acmr = Cesium.Tipsify.calculateACMR({indices : indices, maxIndex : maxIndex, cacheSize : cacheSize});
*/
Tipsify.calculateACMR = function (options) {
options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
const indices = options.indices;
let maximumIndex = options.maximumIndex;
const cacheSize = defaultValue.defaultValue(options.cacheSize, 24);
//>>includeStart('debug', pragmas.debug);
if (!defaultValue.defined(indices)) {
throw new RuntimeError.DeveloperError("indices is required.");
}
//>>includeEnd('debug');
const numIndices = indices.length;
//>>includeStart('debug', pragmas.debug);
if (numIndices < 3 || numIndices % 3 !== 0) {
throw new RuntimeError.DeveloperError("indices length must be a multiple of three.");
}
if (maximumIndex <= 0) {
throw new RuntimeError.DeveloperError("maximumIndex must be greater than zero.");
}
if (cacheSize < 3) {
throw new RuntimeError.DeveloperError("cacheSize must be greater than two.");
}
//>>includeEnd('debug');
// Compute the maximumIndex if not given
if (!defaultValue.defined(maximumIndex)) {
maximumIndex = 0;
let currentIndex = 0;
let intoIndices = indices[currentIndex];
while (currentIndex < numIndices) {
if (intoIndices > maximumIndex) {
maximumIndex = intoIndices;
}
++currentIndex;
intoIndices = indices[currentIndex];
}
}
// Vertex time stamps
const vertexTimeStamps = [];
for (let i = 0; i < maximumIndex + 1; i++) {
vertexTimeStamps[i] = 0;
}
// Cache processing
let s = cacheSize + 1;
for (let j = 0; j < numIndices; ++j) {
if (s - vertexTimeStamps[indices[j]] > cacheSize) {
vertexTimeStamps[indices[j]] = s;
++s;
}
}
return (s - cacheSize + 1) / (numIndices / 3);
};
/**
* Optimizes triangles for the post-vertex shader cache.
*
* @param {Object} options Object with the following properties:
* @param {Number[]} options.indices Lists triads of numbers corresponding to the indices of the vertices
* in the vertex buffer that define the geometry's triangles.
* @param {Number} [options.maximumIndex] The maximum value of the elements in <code>args.indices</code>.
* If not supplied, this value will be computed.
* @param {Number} [options.cacheSize=24] The number of vertices that can be stored in the cache at any one time.
* @returns {Number[]} A list of the input indices in an optimized order.
*
* @exception {DeveloperError} indices length must be a multiple of three.
* @exception {DeveloperError} cacheSize must be greater than two.
*
* @example
* const indices = [0, 1, 2, 3, 4, 5];
* const maxIndex = 5;
* const cacheSize = 3;
* const reorderedIndices = Cesium.Tipsify.tipsify({indices : indices, maxIndex : maxIndex, cacheSize : cacheSize});
*/
Tipsify.tipsify = function (options) {
options = defaultValue.defaultValue(options, defaultValue.defaultValue.EMPTY_OBJECT);
const indices = options.indices;
const maximumIndex = options.maximumIndex;
const cacheSize = defaultValue.defaultValue(options.cacheSize, 24);
let cursor;
function skipDeadEnd(vertices, deadEnd, indices, maximumIndexPlusOne) {
while (deadEnd.length >= 1) {
// while the stack is not empty
const d = deadEnd[deadEnd.length - 1]; // top of the stack
deadEnd.splice(deadEnd.length - 1, 1); // pop the stack
if (vertices[d].numLiveTriangles > 0) {
return d;
}
}
while (cursor < maximumIndexPlusOne) {
if (vertices[cursor].numLiveTriangles > 0) {
++cursor;
return cursor - 1;
}
++cursor;
}
return -1;
}
function getNextVertex(
indices,
cacheSize,
oneRing,
vertices,
s,
deadEnd,
maximumIndexPlusOne
) {
let n = -1;
let p;
let m = -1;
let itOneRing = 0;
while (itOneRing < oneRing.length) {
const index = oneRing[itOneRing];
if (vertices[index].numLiveTriangles) {
p = 0;
if (
s -
vertices[index].timeStamp +
2 * vertices[index].numLiveTriangles <=
cacheSize
) {
p = s - vertices[index].timeStamp;
}
if (p > m || m === -1) {
m = p;
n = index;
}
}
++itOneRing;
}
if (n === -1) {
return skipDeadEnd(vertices, deadEnd, indices, maximumIndexPlusOne);
}
return n;
}
//>>includeStart('debug', pragmas.debug);
if (!defaultValue.defined(indices)) {
throw new RuntimeError.DeveloperError("indices is required.");
}
//>>includeEnd('debug');
const numIndices = indices.length;
//>>includeStart('debug', pragmas.debug);
if (numIndices < 3 || numIndices % 3 !== 0) {
throw new RuntimeError.DeveloperError("indices length must be a multiple of three.");
}
if (maximumIndex <= 0) {
throw new RuntimeError.DeveloperError("maximumIndex must be greater than zero.");
}
if (cacheSize < 3) {
throw new RuntimeError.DeveloperError("cacheSize must be greater than two.");
}
//>>includeEnd('debug');
// Determine maximum index
let maximumIndexPlusOne = 0;
let currentIndex = 0;
let intoIndices = indices[currentIndex];
const endIndex = numIndices;
if (defaultValue.defined(maximumIndex)) {
maximumIndexPlusOne = maximumIndex + 1;
} else {
while (currentIndex < endIndex) {
if (intoIndices > maximumIndexPlusOne) {
maximumIndexPlusOne = intoIndices;
}
++currentIndex;
intoIndices = indices[currentIndex];
}
if (maximumIndexPlusOne === -1) {
return 0;
}
++maximumIndexPlusOne;
}
// Vertices
const vertices = [];
let i;
for (i = 0; i < maximumIndexPlusOne; i++) {
vertices[i] = {
numLiveTriangles: 0,
timeStamp: 0,
vertexTriangles: [],
};
}
currentIndex = 0;
let triangle = 0;
while (currentIndex < endIndex) {
vertices[indices[currentIndex]].vertexTriangles.push(triangle);
++vertices[indices[currentIndex]].numLiveTriangles;
vertices[indices[currentIndex + 1]].vertexTriangles.push(triangle);
++vertices[indices[currentIndex + 1]].numLiveTriangles;
vertices[indices[currentIndex + 2]].vertexTriangles.push(triangle);
++vertices[indices[currentIndex + 2]].numLiveTriangles;
++triangle;
currentIndex += 3;
}
// Starting index
let f = 0;
// Time Stamp
let s = cacheSize + 1;
cursor = 1;
// Process
let oneRing = [];
const deadEnd = []; //Stack
let vertex;
let intoVertices;
let currentOutputIndex = 0;
const outputIndices = [];
const numTriangles = numIndices / 3;
const triangleEmitted = [];
for (i = 0; i < numTriangles; i++) {
triangleEmitted[i] = false;
}
let index;
let limit;
while (f !== -1) {
oneRing = [];
intoVertices = vertices[f];
limit = intoVertices.vertexTriangles.length;
for (let k = 0; k < limit; ++k) {
triangle = intoVertices.vertexTriangles[k];
if (!triangleEmitted[triangle]) {
triangleEmitted[triangle] = true;
currentIndex = triangle + triangle + triangle;
for (let j = 0; j < 3; ++j) {
// Set this index as a possible next index
index = indices[currentIndex];
oneRing.push(index);
deadEnd.push(index);
// Output index
outputIndices[currentOutputIndex] = index;
++currentOutputIndex;
// Cache processing
vertex = vertices[index];
--vertex.numLiveTriangles;
if (s - vertex.timeStamp > cacheSize) {
vertex.timeStamp = s;
++s;
}
++currentIndex;
}
}
}
f = getNextVertex(
indices,
cacheSize,
oneRing,
vertices,
s,
deadEnd,
maximumIndexPlusOne
);
}
return outputIndices;
};
/**
* Content pipeline functions for geometries.
*
* @namespace GeometryPipeline
*
* @see Geometry
*/
const GeometryPipeline = {};
function addTriangle(lines, index, i0, i1, i2) {
lines[index++] = i0;
lines[index++] = i1;
lines[index++] = i1;
lines[index++] = i2;
lines[index++] = i2;
lines[index] = i0;
}
function trianglesToLines(triangles) {
const count = triangles.length;
const size = (count / 3) * 6;
const lines = IndexDatatype.IndexDatatype.createTypedArray(count, size);
let index = 0;
for (let i = 0; i < count; i += 3, index += 6) {
addTriangle(lines, index, triangles[i], triangles[i + 1], triangles[i + 2]);
}
return lines;
}
function triangleStripToLines(triangles) {
const count = triangles.length;
if (count >= 3) {
const size = (count - 2) * 6;
const lines = IndexDatatype.IndexDatatype.createTypedArray(count, size);
addTriangle(lines, 0, triangles[0], triangles[1], triangles[2]);
let index = 6;
for (let i = 3; i < count; ++i, index += 6) {
addTriangle(
lines,
index,
triangles[i - 1],
triangles[i],
triangles[i - 2]
);
}
return lines;
}
return new Uint16Array();
}
function triangleFanToLines(triangles) {
if (triangles.length > 0) {
const count = triangles.length - 1;
const size = (count - 1) * 6;
const lines = IndexDatatype.IndexDatatype.createTypedArray(count, size);
const base = triangles[0];
let index = 0;
for (let i = 1; i < count; ++i, index += 6) {
addTriangle(lines, index, base, triangles[i], triangles[i + 1]);
}
return lines;
}
return new Uint16Array();
}
/**
* Converts a geometry's triangle indices to line indices. If the geometry has an <code>indices</code>
* and its <code>primitiveType</code> is <code>TRIANGLES</code>, <code>TRIANGLE_STRIP</code>,
* <code>TRIANGLE_FAN</code>, it is converted to <code>LINES</code>; otherwise, the geometry is not changed.
* <p>
* This is commonly used to create a wireframe geometry for visual debugging.
* </p>
*
* @param {Geometry} geometry The geometry to modify.
* @returns {Geometry} The modified <code>geometry</code> argument, with its triangle indices converted to lines.
*
* @exception {DeveloperError} geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN.
*
* @example
* geometry = Cesium.GeometryPipeline.toWireframe(geometry);
*/
GeometryPipeline.toWireframe = function (geometry) {
//>>includeStart('debug', pragmas.debug);
if (!defaultValue.defined(geometry)) {
throw new RuntimeError.DeveloperError("geometry is required.");
}
//>>includeEnd('debug');
const indices = geometry.indices;
if (defaultValue.defined(indices)) {
switch (geometry.primitiveType) {
case GeometryAttribute.PrimitiveType.TRIANGLES:
geometry.indices = trianglesToLines(indices);
break;
case GeometryAttribute.PrimitiveType.TRIANGLE_STRIP:
geometry.indices = triangleStripToLines(indices);
break;
case GeometryAttribute.PrimitiveType.TRIANGLE_FAN:
geometry.indices = triangleFanToLines(indices);
break;
//>>includeStart('debug', pragmas.debug);
default:
throw new RuntimeError.DeveloperError(
"geometry.primitiveType must be TRIANGLES, TRIANGLE_STRIP, or TRIANGLE_FAN."
);
//>>includeEnd('debug');
}
geometry.primitiveType = GeometryAttribute.PrimitiveType.LINES;
}
return geometry;
};
/**
* Creates a new {@link Geometry} with <code>LINES</code> representing the provided
* attribute (<code>attributeName</code>) for the provided geometry. This is used to
* visualize vector attributes like normals, tangents, and bitangents.
*
* @param {Geometry} geometry The <code>Geometry</code> instance with the attribute.
* @param {String} [attributeName='normal'] The name of the attribute.
* @param {Number} [length=10000.0] The length of each line segment in meters. This can be negative to point the vector in the opposite direction.
* @returns {Geometry} A new <code>Geometry</code> instance with line segments for the vector.
*
* @exception {DeveloperError} geometry.attributes must have an attribute with the same name as the attributeName parameter.
*
* @example
* const geometry = Cesium.GeometryPipeline.createLineSegmentsForVectors(instance.geometry, 'bitangent', 100000.0);
*/
GeometryPipeline.createLineSegmentsForVectors = function (
geometry,
attributeName,
length
) {
attributeName = defaultValue.defaultValue(attributeName, "normal");
//>>includeStart('debug', pragmas.debug);
if (!defaultValue.defined(geometry)) {
throw new RuntimeError.DeveloperError("geometry is required.");
}
if (!defaultValue.defined(geometry.attributes.position)) {
throw new RuntimeError.DeveloperError("geometry.attributes.position is required.");
}
if (!defaultValue.defined(geometry.attributes[attributeName])) {
throw new RuntimeError.DeveloperError(
`geometry.attributes must have an attribute with the same name as the attributeName parameter, ${attributeName}.`
);
}
//>>includeEnd('debug');
length = defaultValue.defaultValue(length, 10000.0);
const positions = geometry.attributes.position.values;
const vectors = geometry.attributes[attributeName].values;
const positionsLength = positions.length;
const newPositions = new Float64Array(2 * positionsLength);
let j = 0;
for (let i = 0; i < positionsLength; i += 3) {
newPositions[j++] = positions[i];
newPositions[j++] = positions[i + 1];
newPositions[j++] = positions[i + 2];
newPositions[j++] = positions[i] + vectors[i] * length;
newPositions[j++] = positions[i + 1] + vectors[i + 1] * length;
newPositions[j++] = positions[i + 2] + vectors[i + 2] * length;
}
let newBoundingSphere;
const bs = geometry.boundingSphere;
if (defaultValue.defined(bs)) {
newBoundingSphere = new Transforms.BoundingSphere(bs.center, bs.radius + length);
}
return new GeometryAttribute.Geometry({
attributes: {
position: new GeometryAttribute.GeometryAttribute({
componentDatatype: ComponentDatatype.ComponentDatatype.DOUBLE,
componentsPerAttribute: 3,
values: newPositions,
}),
},
primitiveType: GeometryAttribute.PrimitiveType.LINES,
boundingSphere: newBoundingSphere,
});
};
/**
* Creates an object that maps attribute names to unique locations (indices)
* for matching vertex attributes and shader programs.
*
* @param {Geometry} geometry The geometry, which is not modified, to create the object for.
* @returns {Object} An object with attribute name / index pairs.
*
* @example
* const attributeLocations = Cesium.GeometryPipeline.createAttributeLocations(geometry);
* // Example output
* // {
* // 'position' : 0,
* // 'normal' : 1
* // }
*/
GeometryPipeline.createAttributeLocations = function (geometry) {
//>>includeStart('debug', pragmas.debug);
if (!defaultValue.defined(geometry)) {
throw new RuntimeError.DeveloperError("geometry is required.");
}
//>>includeEnd('debug')
// There can be a WebGL performance hit when attribute 0 is disabled, so
// assign attribute locations to well-known attributes.
const semantics = [
"position",
"positionHigh",
"positionLow",
// From VertexFormat.position - after 2D projection and high-precision encoding
"position3DHigh",
"position3DLow",
"position2DHigh",
"position2DLow",
// From Primitive
"pickColor",
// From VertexFormat
"normal",
"st",
"tangent",
"bitangent",
// For shadow volumes
"extrudeDirection",
// From compressing texture coordinates and normals
"compressedAttributes",
];
const attributes = geometry.attributes;
const indices = {};
let j = 0;
let i;
const len = semantics.length;
// Attribute locations for well-known attributes
for (i = 0; i < len; ++i) {
const semantic = semantics[i];
if (defaultValue.defined(attributes[semantic])) {
indices[semantic] = j++;
}
}
// Locations for custom attributes
for (const name in attributes) {
if (attributes.hasOwnProperty(name) && !defaultValue.defined(indices[name])) {
indices[name] = j++;
}
}
return indices;
};
/**
* Reorders a geometry's attributes and <code>indices</code> to achieve better performance from the GPU's pre-vertex-shader cache.
*
* @param {Geometry} geometry The geometry to modify.
* @returns {Geometry} The modified <code>geometry</code> argument, with its attributes and indices reordered for the GPU's pre-vertex-shader cache.
*
* @exception {DeveloperError} Each attribute array in geometry.attributes must have the same number of attributes.
*
*
* @example
* geometry = Cesium.GeometryPipeline.reorderForPreVertexCache(geometry);
*
* @see GeometryPipeline.reorderForPostVertexCache
*/
GeometryPipeline.reorderForPreVertexCache = function (geometry) {
//>>includeStart('debug', pragmas.debug);
if (!defaultValue.defined(geometry)) {
throw new RuntimeError.DeveloperError("geometry is required.");
}
//>>includeEnd('debug');
const numVertices = GeometryAttribute.Geometry.computeNumberOfVertices(geometry);
const indices = geometry.indices;
if (defaultValue.defined(indices)) {
const indexCrossReferenceOldToNew = new Int32Array(numVertices);
for (let i = 0; i < numVertices; i++) {
indexCrossReferenceOldToNew[i] = -1;
}
// Construct cross reference and reorder indices
const indicesIn = indices;
const numIndices = indicesIn.length;
const indicesOut = IndexDatatype.IndexDatatype.createTypedArray(numVertices, numIndices);
let intoIndicesIn = 0;
let intoIndicesOut = 0;
let nextIndex = 0;
let tempIndex;
while (intoIndicesIn < numIndices) {
tempIndex = indexCrossReferenceOldToNew[indicesIn[intoIndicesIn]];
if (tempIndex !== -1) {
indicesOut[intoIndicesOut] = tempIndex;
} else {
tempIndex = indicesIn[intoIndicesIn];
indexCrossReferenceOldToNew[tempIndex] = nextIndex;
indicesOut[intoIndicesOut] = nextIndex;
++nextIndex;
}
++intoIndicesIn;
++intoIndicesOut;
}
geometry.indices = indicesOut;
// Reorder attributes
const attributes = geometry.attributes;
for (const property in attributes) {
if (
attributes.hasOwnProperty(property) &&
defaultValue.defined(attributes[property]) &&
defaultValue.defined(attributes[property].values)
) {
const attribute = attributes[property];
const elementsIn = attribute.values;
let intoElementsIn = 0;
const numComponents = attribute.componentsPerAttribute;
const elementsOut = ComponentDatatype.ComponentDatatype.createTypedArray(
attribute.componentDatatype,
nextIndex * numComponents
);
while (intoElementsIn < numVertices) {
const temp = indexCrossReferenceOldToNew[intoElementsIn];
if (temp !== -1) {
for (let j = 0; j < numComponents; j++) {
elementsOut[numComponents * temp + j] =
elementsIn[numComponents * intoElementsIn + j];
}
}
++intoElementsIn;
}
attribute.values = elementsOut;
}
}
}
return geometry;
};
/**
* Reorders a geometry's <code>indices</code> to achieve better performance from the GPU's
* post vertex-shader cache by using the Tipsify algorithm. If the geometry <code>primitiveType</code>
* is not <code>TRIANGLES</code> or the geometry does not have an <code>indices</code>, this function has no effect.
*
* @param {Geometry} geometry The geometry to modify.
* @param {Number} [cacheCapacity=24] The number of vertices that can be held in the GPU's vertex cache.
* @returns {Geometry} The modified <code>geometry</code> argument, with its indices reordered for the post-vertex-shader cache.
*
* @exception {DeveloperError} cacheCapacity must be greater than two.
*
*
* @example
* geometry = Cesium.GeometryPipeline.reorderForPostVertexCache(geometry);
*
* @see GeometryPipeline.reorderForPreVertexCache
* @see {@link http://gfx.cs.princ0eton.edu/pubs/Sander_2007_%3ETR/tipsy.pdf|Fast Triangle Reordering for Vertex Locality and Reduced Overdraw}
* by Sander, Nehab, and Barczak
*/
GeometryPipeline.reorderForPostVertexCache = function (
geometry,
cacheCapacity
) {
//>>includeStart('debug', pragmas.debug);
if (!defaultValue.defined(geometry)) {
throw new RuntimeError.DeveloperError("geometry is required.");
}
//>>includeEnd('debug');
const indices = geometry.indices;
if (geometry.primitiveType === GeometryAttribute.PrimitiveType.TRIANGLES && defaultValue.defined(indices)) {
const numIndices = indices.length;
let maximumIndex = 0;
for (let j = 0; j < numIndices; j++) {
if (indices[j] > maximumIndex) {
maximumIndex = indices[j];
}
}
geometry.indices = Tipsify.tipsify({
indices: indices,
maximumIndex: maximumIndex,
cacheSize: cacheCapacity,
});
}
return geometry;
};
function copyAttributesDescriptions(attributes) {
const newAttributes = {};
for (const attribute in attributes) {
if (
attributes.hasOwnProperty(attribute) &&
defaultValue.defined(attributes[attribute]) &&
defaultValue.defined(attributes[attribute].values)
) {
const attr = attributes[attribute];
newAttributes[attribute] = new GeometryAttribute.GeometryAttribute({
componentDatatype: attr.componentDatatype,
componentsPerAttribute: attr.componentsPerAttribute,
normalize: attr.normalize,
values: [],
});
}
}
return newAttributes;
}
function copyVertex(destinationAttributes, sourceAttributes, index) {
for (const attribute in sourceAttributes) {
if (
sourceAttributes.hasOwnProperty(attribute) &&
defaultValue.defined(sourceAttributes[attribute]) &&
defaultValue.defined(sourceAttributes[attribute].values)
) {
const attr = sourceAttributes[attribute];
for (let k = 0; k < attr.componentsPerAttribute; ++k) {
destinationAttributes[attribute].values.push(
attr.values[index * attr.componentsPerAttribute + k]
);
}
}
}
}
/**
* Splits a geometry into multiple geometries, if necessary, to ensure that indices in the
* <code>indices</code> fit into unsigned shorts. This is used to meet the WebGL requirements
* when unsigned int indices are not supported.
* <p>
* If the geometry does not have any <code>indices</code>, this function has no effect.
* </p>
*
* @param {Geometry} geometry The geometry to be split into multiple geometries.
* @returns {Geometry[]} An array of geometries, each with indices that fit into unsigned shorts.
*
* @exception {DeveloperError} geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS
* @exception {DeveloperError} All geometry attribute lists must have the same number of attributes.
*
* @example
* const geometries = Cesium.GeometryPipeline.fitToUnsignedShortIndices(geometry);
*/
GeometryPipeline.fitToUnsignedShortIndices = function (geometry) {
//>>includeStart('debug', pragmas.debug);
if (!defaultValue.defined(geometry)) {
throw new RuntimeError.DeveloperError("geometry is required.");
}
if (
defaultValue.defined(geometry.indices) &&
geometry.primitiveType !== GeometryAttribute.PrimitiveType.TRIANGLES &&
geometry.primitiveType !== GeometryAttribute.PrimitiveType.LINES &&
geometry.primitiveType !== GeometryAttribute.PrimitiveType.POINTS
) {
throw new RuntimeError.DeveloperError(
"geometry.primitiveType must equal to PrimitiveType.TRIANGLES, PrimitiveType.LINES, or PrimitiveType.POINTS."
);
}
//>>includeEnd('debug');
const geometries = [];
// If there's an index list and more than 64K attributes, it is possible that
// some indices are outside the range of unsigned short [0, 64K - 1]
const numberOfVertices = GeometryAttribute.Geometry.computeNumberOfVertices(geometry);
if (
defaultValue.defined(geometry.indices) &&
numberOfVertices >= ComponentDatatype.CesiumMath.SIXTY_FOUR_KILOBYTES
) {
let oldToNewIndex = [];
let newIndices = [];
let currentIndex = 0;
let newAttributes = copyAttributesDescriptions(geometry.attributes);
const originalIndices = geometry.indices;
const numberOfIndices = originalIndices.length;
let indicesPerPrimitive;
if (geometry.primitiveType === GeometryAttribute.PrimitiveType.TRIANGLES) {
indicesPerPrimitive = 3;
} else if (geometry.primitiveType === GeometryAttribute.PrimitiveType.LINES) {
indicesPerPrimitive = 2;
} else if (geometry.primitiveType === GeometryAttribute.PrimitiveType.POINTS) {
indicesPerPrimitive = 1;
}
for (let j = 0; j < numberOfIndices; j += indicesPerPrimitive) {
for (let k = 0; k < indicesPerPrimitive; ++k) {
const x = originalIndices[j + k];
let i = oldToNewIndex[x];
if (!defaultValue.defined(i)) {
i = currentIndex++;
oldToNewIndex[x] = i;
copyVertex(newAttributes, geometry.attributes, x);
}
newIndices.push(i);
}
if (
currentIndex + indicesPerPrimitive >=
ComponentDatatype.CesiumMath.SIXTY_FOUR_KILOBYTES
) {
geometries.push(
new GeometryAttribute.Geometry({
attributes: newAttributes,
indices: newIndices,
primitiveType: geometry.primitiveType,
boundingSphere: geometry.boundingSphere,
boundingSphereCV: geometry.boundingSphereCV,
})
);
// Reset for next vertex-array
oldToNewIndex = [];
newIndices = [];
currentIndex = 0;
newAttributes = copyAttributesDescriptions(geometry.attributes);
}
}
if (newIndices.length !== 0) {
geometries.push(
new GeometryAttribute.Geometry({
attributes: newAttributes,
indices: newIndices,
primitiveType: geometry.primitiveType,
boundingSphere: geometry.boundingSphere,
boundingSphereCV: geometry.boundingSphereCV,
})
);
}
} else {
// No need to split into multiple geometries
geometries.push(geometry);
}
return geometries;
};
const scratchProjectTo2DCartesian3 = new Matrix2.Cartesian3();
const scratchProjectTo2DCartographic = new Matrix2.Cartographic();
/**
* Projects a geometry's 3D <code>position</code> attribute to 2D, replacing the <code>position</code>
* attribute with separate <code>position3D</code> and <code>position2D</code> attributes.
* <p>
* If the geometry does not have a <code>position</code>, this function has no effect.
* </p>
*
* @param {Geometry} geometry The geometry to modify.
* @param {String} attributeName The name of the attribute.
* @param {String} attributeName3D The name of the attribute in 3D.
* @param {String} attributeName2D The name of the attribute in 2D.
* @param {Object} [projection=new GeographicProjection()] The projection to use.
* @returns {Geometry} The modified <code>geometry</code> argument with <code>position3D</code> and <code>position2D</code> attributes.
*
* @exception {DeveloperError} geometry must have attribute matching the attributeName argument.
* @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE.
* @exception {DeveloperError} Could not project a point to 2D.
*
* @example
* geometry = Cesium.GeometryPipeline.projectTo2D(geometry, 'position', 'position3D', 'position2D');
*/
GeometryPipeline.projectTo2D = function (
geometry,
attributeName,
attributeName3D,
attributeName2D,
projection
) {
//>>includeStart('debug', pragmas.debug);
if (!defaultValue.defined(geometry)) {
throw new RuntimeError.DeveloperError("geometry is required.");
}
if (!defaultValue.defined(attributeName)) {
throw new RuntimeError.DeveloperError("attributeName is required.");
}
if (!defaultValue.defined(attributeName3D)) {
throw new RuntimeError.DeveloperError("attributeName3D is required.");
}
if (!defaultValue.defined(attributeName2D)) {
throw new RuntimeError.DeveloperError("attributeName2D is required.");
}
if (!defaultValue.defined(geometry.attributes[attributeName])) {
throw new RuntimeError.DeveloperError(
`geometry must have attribute matching the attributeName argument: ${attributeName}.`
);
}
if (
geometry.attributes[attributeName].componentDatatype !==
ComponentDatatype.ComponentDatatype.DOUBLE
) {
throw new RuntimeError.DeveloperError(
"The attribute componentDatatype must be ComponentDatatype.DOUBLE."
);
}
//>>includeEnd('debug');
const attribute = geometry.attributes[attributeName];
projection = defaultValue.defined(projection) ? projection : new Transforms.GeographicProjection();
const ellipsoid = projection.ellipsoid;
// Project original values to 2D.
const values3D = attribute.values;
const projectedValues = new Float64Array(values3D.length);
let index = 0;
for (let i = 0; i < values3D.length; i += 3) {
const value = Matrix2.Cartesian3.fromArray(
values3D,
i,
scratchProjectTo2DCartesian3
);
const lonLat = ellipsoid.cartesianToCartographic(
value,
scratchProjectTo2DCartographic
);
//>>includeStart('debug', pragmas.debug);
if (!defaultValue.defined(lonLat)) {
throw new RuntimeError.DeveloperError(
`Could not project point (${value.x}, ${value.y}, ${value.z}) to 2D.`
);
}
//>>includeEnd('debug');
const projectedLonLat = projection.project(
lonLat,
scratchProjectTo2DCartesian3
);
projectedValues[index++] = projectedLonLat.x;
projectedValues[index++] = projectedLonLat.y;
projectedValues[index++] = projectedLonLat.z;
}
// Rename original cartesians to WGS84 cartesians.
geometry.attributes[attributeName3D] = attribute;
// Replace original cartesians with 2D projected cartesians
geometry.attributes[attributeName2D] = new GeometryAttribute.GeometryAttribute({
componentDatatype: ComponentDatatype.ComponentDatatype.DOUBLE,
componentsPerAttribute: 3,
values: projectedValues,
});
delete geometry.attributes[attributeName];
return geometry;
};
const encodedResult = {
high: 0.0,
low: 0.0,
};
/**
* Encodes floating-point geometry attribute values as two separate attributes to improve
* rendering precision.
* <p>
* This is commonly used to create high-precision position vertex attributes.
* </p>
*
* @param {Geometry} geometry The geometry to modify.
* @param {String} attributeName The name of the attribute.
* @param {String} attributeHighName The name of the attribute for the encoded high bits.
* @param {String} attributeLowName The name of the attribute for the encoded low bits.
* @returns {Geometry} The modified <code>geometry</code> argument, with its encoded attribute.
*
* @exception {DeveloperError} geometry must have attribute matching the attributeName argument.
* @exception {DeveloperError} The attribute componentDatatype must be ComponentDatatype.DOUBLE.
*
* @example
* geometry = Cesium.GeometryPipeline.encodeAttribute(geometry, 'position3D', 'position3DHigh', 'position3DLow');
*/
GeometryPipeline.encodeAttribute = function (
geometry,
attributeName,
attributeHighName,
attributeLowName
) {
//>>includeStart('debug', pragmas.debug);
if (!defaultValue.defined(geometry)) {
throw new RuntimeError.DeveloperError("geometry is required.");
}
if (!defaultValue.defined(attributeName)) {
throw new RuntimeError.DeveloperError("attributeName is required.");
}
if (!defaultValue.defined(attributeHighName)) {
throw new RuntimeError.DeveloperError("attributeHighName is required.");
}
if (!defaultValue.defined(attributeLowName)) {
throw new RuntimeError.DeveloperError("attributeLowName is required.");
}
if (!defaultValue.defined(geometry.attributes[attributeName])) {
throw new RuntimeError.DeveloperError(
`geometry must have attribute matching the attributeName argument: ${attributeName}.`
);
}
if (
geometry.attributes[attributeName].componentDatatype !==
ComponentDatatype.ComponentDatatype.DOUBLE
) {
throw new RuntimeError.DeveloperError(
"The attribute componentDatatype must be ComponentDatatype.DOUBLE."
);
}
//>>includeEnd('debug');
const attribute = geometry.attributes[attributeName];
const values = attribute.values;
const length = values.length;
const highValues = new Float32Array(length);
const lowValues = new Float32Array(length);
for (let i = 0; i < length; ++i) {
EncodedCartesian3.EncodedCartesian3.encode(values[i], encodedResult);
highValues[i] = encodedResult.high;
lowValues[i] = encodedResult.low;
}
const componentsPerAttribute = attribute.componentsPerAttribute;
geometry.attributes[attributeHighName] = new GeometryAttribute.GeometryAttribute({
componentDatatype: ComponentDatatype.ComponentDatatype.FLOAT,
componentsPerAttribute: componentsPerAttribute,
values: highValues,
});
geometry.attributes[attributeLowName] = new GeometryAttribute.GeometryAttribute({
componentDatatype: ComponentDatatype.ComponentDatatype.FLOAT,
componentsPerAttribute: componentsPerAttribute,
values: lowValues,
});
delete geometry.attributes[attributeName];
return geometry;
};
let scratchCartesian3 = new Matrix2.Cartesian3();
function transformPoint(matrix, attribute) {
if (defaultValue.defined(attribute)) {
const values = attribute.values;
const length = values.length;
for (let i = 0; i < length; i += 3) {
Matrix2.Cartesian3.unpack(values, i, scratchCartesian3);
Matrix2.Matrix4.multiplyByPoint(matrix, scratchCartesian3, scratchCartesian3);
Matrix2.Cartesian3.pack(scratchCartesian3, values, i);
}
}
}
function transformVector(matrix, attribute) {
if (defaultValue.defined(attribute)) {
const values = attribute.values;
const length = values.length;
for (let i = 0; i < length; i += 3) {
Matrix2.Cartesian3.unpack(values, i, scratchCartesian3);
Matrix2.Matrix3.multiplyByVector(matrix, scratchCartesian3, scratchCartesian3);
scratchCartesian3 = Matrix2.Cartesian3.normalize(
scratchCartesian3,
scratchCartesian3
);
Matrix2.Cartesian3.pack(scratchCartesian3, values, i);
}
}
}
const inverseTranspose = new Matrix2.Matrix4();
const normalMatrix = new Matrix2.Matrix3();
/**
* Transforms a geometry instance to world coordinates. This changes
* the instance's <code>modelMatrix</code> to {@link Matrix4.IDENTITY} and transforms the
* following attributes if they are present: <code>position</code>, <code>normal</code>,
* <code>tangent</code>, and <code>bitangent</code>.
*
* @param {GeometryInstance} instance The geometry instance to modify.
* @returns {GeometryInstance} The modified <code>instance</code> argument, with its attributes transforms to world coordinates.
*
* @example
* Cesium.GeometryPipeline.transformToWorldCoordinates(instance);
*/
GeometryPipeline.transformToWorldCoordinates = function (instance) {
//>>includeStart('debug', pragmas.debug);
if (!defaultValue.defined(instance)) {
throw new RuntimeError.DeveloperError("instance is required.");
}
//>>includeEnd('debug');
const modelMatrix = instance.modelMatrix;
if (Matrix2.Matrix4.equals(modelMatrix, Matrix2.Matrix4.IDENTITY)) {
// Already in world coordinates
return instance;
}
const attributes = instance.geometry.attributes;
// Transform attributes in known vertex formats
transformPoint(modelMatrix, attributes.position);
transformPoint(modelMatrix, attributes.prevPosition);
transformPoint(modelMatrix, attributes.nextPosition);
if (
defaultValue.defined(attributes.normal) ||
defaultValue.defined(attributes.tangent) ||
defaultValue.defined(attributes.bitangent)
) {
Matrix2.Matrix4.inverse(modelMatrix, inverseTranspose);
Matrix2.Matrix4.transpose(inverseTranspose, inverseTranspose);
Matrix2.Matrix4.getMatrix3(inverseTranspose, normalMatrix);
transformVector(normalMatrix, attributes.normal);
transformVector(normalMatrix, attributes.tangent);
transformVector(normalMatrix, attributes.bitangent);
}
const boundingSphere = instance.geometry.boundingSphere;
if (defaultValue.defined(boundingSphere)) {
instance.geometry.boundingSphere = Transforms.BoundingSphere.transform(
boundingSphere,
modelMatrix,
boundingSphere
);
}
instance.modelMatrix = Matrix2.Matrix4.clone(Matrix2.Matrix4.IDENTITY);
return instance;
};
function findAttributesInAllGeometries(instances, propertyName) {
const length = instances.length;
const attributesInAllGeometries = {};
const attributes0 = instances[0][propertyName].attributes;
let name;
for (name in attributes0) {
if (
attributes0.hasOwnProperty(name) &&
defaultValue.defined(attributes0[name]) &&
defaultValue.defined(attributes0[name].values)
) {
const attribute = attributes0[name];
let numberOfComponents = attribute.values.length;
let inAllGeometries = true;
// Does this same attribute exist in all geometries?
for (let i = 1; i < length; ++i) {
const otherAttribute = instances[i][propertyName].attributes[name];
if (
!defaultValue.defined(otherAttribute) ||
attribute.componentDatatype !== otherAttribute.componentDatatype ||
attribute.componentsPerAttribute !==
otherAttribute.componentsPerAttribute ||
attribute.normalize !== otherAttribute.normalize
) {
inAllGeometries = false;
break;
}
numberOfComponents += otherAttribute.values.length;
}
if (inAllGeometries) {
attributesInAllGeometries[name] = new GeometryAttribute.GeometryAttribute({
componentDatatype: attribute.componentDatatype,
componentsPerAttribute: attribute.componentsPerAttribute,
normalize: attribute.normalize,
values: ComponentDatatype.ComponentDatatype.createTypedArray(
attribute.componentDatatype,
numberOfComponents
),
});
}
}
}
return attributesInAllGeometries;
}
const tempScratch = new Matrix2.Cartesian3();
function combineGeometries(instances, propertyName) {
const length = instances.length;
let name;
let i;
let j;
let k;
const m = instances[0].modelMatrix;
const haveIndices = defaultValue.defined(instances[0][propertyName].indices);
const primitiveType = instances[0][propertyName].primitiveType;
//>>includeStart('debug', pragmas.debug);
for (i = 1; i < length; ++i) {
if (!Matrix2.Matrix4.equals(instances[i].modelMatrix, m)) {
throw new RuntimeError.DeveloperError("All instances must have the same modelMatrix.");
}
if (defaultValue.defined(instances[i][propertyName].indices) !== haveIndices) {
throw new RuntimeError.DeveloperError(
"All instance geometries must have an indices or not have one."
);
}
if (instances[i][propertyName].primitiveType !== primitiveType) {
throw new RuntimeError.DeveloperError(
"All instance geometries must have the same primitiveType."
);
}
}
//>>includeEnd('debug');
// Find subset of attributes in all geometries
const attributes = findAttributesInAllGeometries(instances, propertyName);
let values;
let sourceValues;
let sourceValuesLength;
// Combine attributes from each geometry into a single typed array
for (name in attributes) {
if (attributes.hasOwnProperty(name)) {
values = attributes[name].values;
k = 0;
for (i = 0; i < length; ++i) {
sourceValues = instances[i][propertyName].attributes[name].values;
sourceValuesLength = sourceValues.length;
for (j = 0; j < sourceValuesLength; ++j) {
values[k++] = sourceValues[j];
}
}
}
}
// Combine index lists
let indices;
if (haveIndices) {
let numberOfIndices = 0;
for (i = 0; i < length; ++i) {
numberOfIndices += instances[i][propertyName].indices.length;
}
const numberOfVertices = GeometryAttribute.Geometry.computeNumberOfVertices(
new GeometryAttribute.Geometry({
attributes: attributes,
primitiveType: GeometryAttribute.PrimitiveType.POINTS,
})
);
const destIndices = IndexDatatype.IndexDatatype.createTypedArray(
numberOfVertices,
numberOfIndices
);
let destOffset = 0;
let offset = 0;
for (i = 0; i < length; ++i) {
const sourceIndices = instances[i][propertyName].indices;
const sourceIndicesLen = sourceIndices.length;
for (k = 0; k < sourceIndicesLen; ++k) {
destIndices[destOffset++] = offset + sourceIndices[k];
}
offset += GeometryAttribute.Geometry.computeNumberOfVertices(instances[i][propertyName]);
}
indices = destIndices;
}
// Create bounding sphere that includes all instances
let center = new Ma