/**
* Cesium - https://github.com/CesiumGS/cesium
*
* Copyright 2011-2020 Cesium Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Columbus View (Pat. Pend.)
*
* Portions licensed separately.
* See https://github.com/CesiumGS/cesium/blob/main/LICENSE.md for full licensing details.
*/
define(['exports', './Matrix2-265d9610', './RuntimeError-5b082e8f', './when-4bbc8319', './ComponentDatatype-aad54330', './combine-e9466e32'], (function (exports, Matrix2, RuntimeError, when, ComponentDatatype, combine) { 'use strict';
/**
* A simple map projection where longitude and latitude are linearly mapped to X and Y by multiplying
* them by the {@link Ellipsoid#maximumRadius}. This projection
* is commonly known as geographic, equirectangular, equidistant cylindrical, or plate carrée. It
* is also known as EPSG:4326.
*
* @alias GeographicProjection
* @constructor
*
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid.
*
* @see WebMercatorProjection
*/
function GeographicProjection(ellipsoid) {
this._ellipsoid = when.defaultValue(ellipsoid, Matrix2.Ellipsoid.WGS84);
this._semimajorAxis = this._ellipsoid.maximumRadius;
this._oneOverSemimajorAxis = 1.0 / this._semimajorAxis;
}
Object.defineProperties(GeographicProjection.prototype, {
/**
* Gets the {@link Ellipsoid}.
*
* @memberof GeographicProjection.prototype
*
* @type {Ellipsoid}
* @readonly
*/
ellipsoid: {
get: function () {
return this._ellipsoid;
},
},
});
/**
* Projects a set of {@link Cartographic} coordinates, in radians, to map coordinates, in meters.
* X and Y are the longitude and latitude, respectively, multiplied by the maximum radius of the
* ellipsoid. Z is the unmodified height.
*
* @param {Cartographic} cartographic The coordinates to project.
* @param {Cartesian3} [result] An instance into which to copy the result. If this parameter is
* undefined, a new instance is created and returned.
* @returns {Cartesian3} The projected coordinates. If the result parameter is not undefined, the
* coordinates are copied there and that instance is returned. Otherwise, a new instance is
* created and returned.
*/
GeographicProjection.prototype.project = function (cartographic, result) {
// Actually this is the special case of equidistant cylindrical called the plate carree
const semimajorAxis = this._semimajorAxis;
const x = cartographic.longitude * semimajorAxis;
const y = cartographic.latitude * semimajorAxis;
const z = cartographic.height;
if (!when.defined(result)) {
return new Matrix2.Cartesian3(x, y, z);
}
result.x = x;
result.y = y;
result.z = z;
return result;
};
/**
* Unprojects a set of projected {@link Cartesian3} coordinates, in meters, to {@link Cartographic}
* coordinates, in radians. Longitude and Latitude are the X and Y coordinates, respectively,
* divided by the maximum radius of the ellipsoid. Height is the unmodified Z coordinate.
*
* @param {Cartesian3} cartesian The Cartesian position to unproject with height (z) in meters.
* @param {Cartographic} [result] An instance into which to copy the result. If this parameter is
* undefined, a new instance is created and returned.
* @returns {Cartographic} The unprojected coordinates. If the result parameter is not undefined, the
* coordinates are copied there and that instance is returned. Otherwise, a new instance is
* created and returned.
*/
GeographicProjection.prototype.unproject = function (cartesian, result) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(cartesian)) {
throw new RuntimeError.DeveloperError("cartesian is required");
}
//>>includeEnd('debug');
const oneOverEarthSemimajorAxis = this._oneOverSemimajorAxis;
const longitude = cartesian.x * oneOverEarthSemimajorAxis;
const latitude = cartesian.y * oneOverEarthSemimajorAxis;
const height = cartesian.z;
if (!when.defined(result)) {
return new Matrix2.Cartographic(longitude, latitude, height);
}
result.longitude = longitude;
result.latitude = latitude;
result.height = height;
return result;
};
/**
* This enumerated type is used in determining where, relative to the frustum, an
* object is located. The object can either be fully contained within the frustum (INSIDE),
* partially inside the frustum and partially outside (INTERSECTING), or somewhere entirely
* outside of the frustum's 6 planes (OUTSIDE).
*
* @enum {Number}
*/
const Intersect = {
/**
* Represents that an object is not contained within the frustum.
*
* @type {Number}
* @constant
*/
OUTSIDE: -1,
/**
* Represents that an object intersects one of the frustum's planes.
*
* @type {Number}
* @constant
*/
INTERSECTING: 0,
/**
* Represents that an object is fully within the frustum.
*
* @type {Number}
* @constant
*/
INSIDE: 1,
};
var Intersect$1 = Object.freeze(Intersect);
/**
* Represents the closed interval [start, stop].
* @alias Interval
* @constructor
*
* @param {Number} [start=0.0] The beginning of the interval.
* @param {Number} [stop=0.0] The end of the interval.
*/
function Interval(start, stop) {
/**
* The beginning of the interval.
* @type {Number}
* @default 0.0
*/
this.start = when.defaultValue(start, 0.0);
/**
* The end of the interval.
* @type {Number}
* @default 0.0
*/
this.stop = when.defaultValue(stop, 0.0);
}
/**
* A bounding sphere with a center and a radius.
* @alias BoundingSphere
* @constructor
*
* @param {Cartesian3} [center=Cartesian3.ZERO] The center of the bounding sphere.
* @param {Number} [radius=0.0] The radius of the bounding sphere.
*
* @see AxisAlignedBoundingBox
* @see BoundingRectangle
* @see Packable
*/
function BoundingSphere(center, radius) {
/**
* The center point of the sphere.
* @type {Cartesian3}
* @default {@link Cartesian3.ZERO}
*/
this.center = Matrix2.Cartesian3.clone(when.defaultValue(center, Matrix2.Cartesian3.ZERO));
/**
* The radius of the sphere.
* @type {Number}
* @default 0.0
*/
this.radius = when.defaultValue(radius, 0.0);
}
const fromPointsXMin = new Matrix2.Cartesian3();
const fromPointsYMin = new Matrix2.Cartesian3();
const fromPointsZMin = new Matrix2.Cartesian3();
const fromPointsXMax = new Matrix2.Cartesian3();
const fromPointsYMax = new Matrix2.Cartesian3();
const fromPointsZMax = new Matrix2.Cartesian3();
const fromPointsCurrentPos = new Matrix2.Cartesian3();
const fromPointsScratch = new Matrix2.Cartesian3();
const fromPointsRitterCenter = new Matrix2.Cartesian3();
const fromPointsMinBoxPt = new Matrix2.Cartesian3();
const fromPointsMaxBoxPt = new Matrix2.Cartesian3();
const fromPointsNaiveCenterScratch = new Matrix2.Cartesian3();
const volumeConstant = (4.0 / 3.0) * ComponentDatatype.CesiumMath.PI;
/**
* Computes a tight-fitting bounding sphere enclosing a list of 3D Cartesian points.
* The bounding sphere is computed by running two algorithms, a naive algorithm and
* Ritter's algorithm. The smaller of the two spheres is used to ensure a tight fit.
*
* @param {Cartesian3[]} [positions] An array of points that the bounding sphere will enclose. Each point must have x
, y
, and z
properties.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*
* @see {@link http://help.agi.com/AGIComponents/html/BlogBoundingSphere.htm|Bounding Sphere computation article}
*/
BoundingSphere.fromPoints = function (positions, result) {
if (!when.defined(result)) {
result = new BoundingSphere();
}
if (!when.defined(positions) || positions.length === 0) {
result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
const currentPos = Matrix2.Cartesian3.clone(positions[0], fromPointsCurrentPos);
const xMin = Matrix2.Cartesian3.clone(currentPos, fromPointsXMin);
const yMin = Matrix2.Cartesian3.clone(currentPos, fromPointsYMin);
const zMin = Matrix2.Cartesian3.clone(currentPos, fromPointsZMin);
const xMax = Matrix2.Cartesian3.clone(currentPos, fromPointsXMax);
const yMax = Matrix2.Cartesian3.clone(currentPos, fromPointsYMax);
const zMax = Matrix2.Cartesian3.clone(currentPos, fromPointsZMax);
const numPositions = positions.length;
let i;
for (i = 1; i < numPositions; i++) {
Matrix2.Cartesian3.clone(positions[i], currentPos);
const x = currentPos.x;
const y = currentPos.y;
const z = currentPos.z;
// Store points containing the the smallest and largest components
if (x < xMin.x) {
Matrix2.Cartesian3.clone(currentPos, xMin);
}
if (x > xMax.x) {
Matrix2.Cartesian3.clone(currentPos, xMax);
}
if (y < yMin.y) {
Matrix2.Cartesian3.clone(currentPos, yMin);
}
if (y > yMax.y) {
Matrix2.Cartesian3.clone(currentPos, yMax);
}
if (z < zMin.z) {
Matrix2.Cartesian3.clone(currentPos, zMin);
}
if (z > zMax.z) {
Matrix2.Cartesian3.clone(currentPos, zMax);
}
}
// Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
const xSpan = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(xMax, xMin, fromPointsScratch)
);
const ySpan = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(yMax, yMin, fromPointsScratch)
);
const zSpan = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(zMax, zMin, fromPointsScratch)
);
// Set the diameter endpoints to the largest span.
let diameter1 = xMin;
let diameter2 = xMax;
let maxSpan = xSpan;
if (ySpan > maxSpan) {
maxSpan = ySpan;
diameter1 = yMin;
diameter2 = yMax;
}
if (zSpan > maxSpan) {
maxSpan = zSpan;
diameter1 = zMin;
diameter2 = zMax;
}
// Calculate the center of the initial sphere found by Ritter's algorithm
const ritterCenter = fromPointsRitterCenter;
ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
// Calculate the radius of the initial sphere found by Ritter's algorithm
let radiusSquared = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
);
let ritterRadius = Math.sqrt(radiusSquared);
// Find the center of the sphere found using the Naive method.
const minBoxPt = fromPointsMinBoxPt;
minBoxPt.x = xMin.x;
minBoxPt.y = yMin.y;
minBoxPt.z = zMin.z;
const maxBoxPt = fromPointsMaxBoxPt;
maxBoxPt.x = xMax.x;
maxBoxPt.y = yMax.y;
maxBoxPt.z = zMax.z;
const naiveCenter = Matrix2.Cartesian3.midpoint(
minBoxPt,
maxBoxPt,
fromPointsNaiveCenterScratch
);
// Begin 2nd pass to find naive radius and modify the ritter sphere.
let naiveRadius = 0;
for (i = 0; i < numPositions; i++) {
Matrix2.Cartesian3.clone(positions[i], currentPos);
// Find the furthest point from the naive center to calculate the naive radius.
const r = Matrix2.Cartesian3.magnitude(
Matrix2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
);
if (r > naiveRadius) {
naiveRadius = r;
}
// Make adjustments to the Ritter Sphere to include all points.
const oldCenterToPointSquared = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
);
if (oldCenterToPointSquared > radiusSquared) {
const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
// Calculate new radius to include the point that lies outside
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
// Calculate center of new Ritter sphere
const oldToNew = oldCenterToPoint - ritterRadius;
ritterCenter.x =
(ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
oldCenterToPoint;
ritterCenter.y =
(ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
oldCenterToPoint;
ritterCenter.z =
(ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
oldCenterToPoint;
}
}
if (ritterRadius < naiveRadius) {
Matrix2.Cartesian3.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Matrix2.Cartesian3.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
const defaultProjection = new GeographicProjection();
const fromRectangle2DLowerLeft = new Matrix2.Cartesian3();
const fromRectangle2DUpperRight = new Matrix2.Cartesian3();
const fromRectangle2DSouthwest = new Matrix2.Cartographic();
const fromRectangle2DNortheast = new Matrix2.Cartographic();
/**
* Computes a bounding sphere from a rectangle projected in 2D.
*
* @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
* @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromRectangle2D = function (rectangle, projection, result) {
return BoundingSphere.fromRectangleWithHeights2D(
rectangle,
projection,
0.0,
0.0,
result
);
};
/**
* Computes a bounding sphere from a rectangle projected in 2D. The bounding sphere accounts for the
* object's minimum and maximum heights over the rectangle.
*
* @param {Rectangle} [rectangle] The rectangle around which to create a bounding sphere.
* @param {Object} [projection=GeographicProjection] The projection used to project the rectangle into 2D.
* @param {Number} [minimumHeight=0.0] The minimum height over the rectangle.
* @param {Number} [maximumHeight=0.0] The maximum height over the rectangle.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromRectangleWithHeights2D = function (
rectangle,
projection,
minimumHeight,
maximumHeight,
result
) {
if (!when.defined(result)) {
result = new BoundingSphere();
}
if (!when.defined(rectangle)) {
result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
projection = when.defaultValue(projection, defaultProjection);
Matrix2.Rectangle.southwest(rectangle, fromRectangle2DSouthwest);
fromRectangle2DSouthwest.height = minimumHeight;
Matrix2.Rectangle.northeast(rectangle, fromRectangle2DNortheast);
fromRectangle2DNortheast.height = maximumHeight;
const lowerLeft = projection.project(
fromRectangle2DSouthwest,
fromRectangle2DLowerLeft
);
const upperRight = projection.project(
fromRectangle2DNortheast,
fromRectangle2DUpperRight
);
const width = upperRight.x - lowerLeft.x;
const height = upperRight.y - lowerLeft.y;
const elevation = upperRight.z - lowerLeft.z;
result.radius =
Math.sqrt(width * width + height * height + elevation * elevation) * 0.5;
const center = result.center;
center.x = lowerLeft.x + width * 0.5;
center.y = lowerLeft.y + height * 0.5;
center.z = lowerLeft.z + elevation * 0.5;
return result;
};
const fromRectangle3DScratch = [];
/**
* Computes a bounding sphere from a rectangle in 3D. The bounding sphere is created using a subsample of points
* on the ellipsoid and contained in the rectangle. It may not be accurate for all rectangles on all types of ellipsoids.
*
* @param {Rectangle} [rectangle] The valid rectangle used to create a bounding sphere.
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid used to determine positions of the rectangle.
* @param {Number} [surfaceHeight=0.0] The height above the surface of the ellipsoid.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromRectangle3D = function (
rectangle,
ellipsoid,
surfaceHeight,
result
) {
ellipsoid = when.defaultValue(ellipsoid, Matrix2.Ellipsoid.WGS84);
surfaceHeight = when.defaultValue(surfaceHeight, 0.0);
if (!when.defined(result)) {
result = new BoundingSphere();
}
if (!when.defined(rectangle)) {
result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
const positions = Matrix2.Rectangle.subsample(
rectangle,
ellipsoid,
surfaceHeight,
fromRectangle3DScratch
);
return BoundingSphere.fromPoints(positions, result);
};
/**
* Computes a tight-fitting bounding sphere enclosing a list of 3D points, where the points are
* stored in a flat array in X, Y, Z, order. The bounding sphere is computed by running two
* algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
* ensure a tight fit.
*
* @param {Number[]} [positions] An array of points that the bounding sphere will enclose. Each point
* is formed from three elements in the array in the order X, Y, Z.
* @param {Cartesian3} [center=Cartesian3.ZERO] The position to which the positions are relative, which need not be the
* origin of the coordinate system. This is useful when the positions are to be used for
* relative-to-center (RTC) rendering.
* @param {Number} [stride=3] The number of array elements per vertex. It must be at least 3, but it may
* be higher. Regardless of the value of this parameter, the X coordinate of the first position
* is at array index 0, the Y coordinate is at array index 1, and the Z coordinate is at array index
* 2. When stride is 3, the X coordinate of the next position then begins at array index 3. If
* the stride is 5, however, two array elements are skipped and the next position begins at array
* index 5.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*
* @example
* // Compute the bounding sphere from 3 positions, each specified relative to a center.
* // In addition to the X, Y, and Z coordinates, the points array contains two additional
* // elements per point which are ignored for the purpose of computing the bounding sphere.
* const center = new Cesium.Cartesian3(1.0, 2.0, 3.0);
* const points = [1.0, 2.0, 3.0, 0.1, 0.2,
* 4.0, 5.0, 6.0, 0.1, 0.2,
* 7.0, 8.0, 9.0, 0.1, 0.2];
* const sphere = Cesium.BoundingSphere.fromVertices(points, center, 5);
*
* @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
*/
BoundingSphere.fromVertices = function (positions, center, stride, result) {
if (!when.defined(result)) {
result = new BoundingSphere();
}
if (!when.defined(positions) || positions.length === 0) {
result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
center = when.defaultValue(center, Matrix2.Cartesian3.ZERO);
stride = when.defaultValue(stride, 3);
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.number.greaterThanOrEquals("stride", stride, 3);
//>>includeEnd('debug');
const currentPos = fromPointsCurrentPos;
currentPos.x = positions[0] + center.x;
currentPos.y = positions[1] + center.y;
currentPos.z = positions[2] + center.z;
const xMin = Matrix2.Cartesian3.clone(currentPos, fromPointsXMin);
const yMin = Matrix2.Cartesian3.clone(currentPos, fromPointsYMin);
const zMin = Matrix2.Cartesian3.clone(currentPos, fromPointsZMin);
const xMax = Matrix2.Cartesian3.clone(currentPos, fromPointsXMax);
const yMax = Matrix2.Cartesian3.clone(currentPos, fromPointsYMax);
const zMax = Matrix2.Cartesian3.clone(currentPos, fromPointsZMax);
const numElements = positions.length;
let i;
for (i = 0; i < numElements; i += stride) {
const x = positions[i] + center.x;
const y = positions[i + 1] + center.y;
const z = positions[i + 2] + center.z;
currentPos.x = x;
currentPos.y = y;
currentPos.z = z;
// Store points containing the the smallest and largest components
if (x < xMin.x) {
Matrix2.Cartesian3.clone(currentPos, xMin);
}
if (x > xMax.x) {
Matrix2.Cartesian3.clone(currentPos, xMax);
}
if (y < yMin.y) {
Matrix2.Cartesian3.clone(currentPos, yMin);
}
if (y > yMax.y) {
Matrix2.Cartesian3.clone(currentPos, yMax);
}
if (z < zMin.z) {
Matrix2.Cartesian3.clone(currentPos, zMin);
}
if (z > zMax.z) {
Matrix2.Cartesian3.clone(currentPos, zMax);
}
}
// Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
const xSpan = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(xMax, xMin, fromPointsScratch)
);
const ySpan = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(yMax, yMin, fromPointsScratch)
);
const zSpan = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(zMax, zMin, fromPointsScratch)
);
// Set the diameter endpoints to the largest span.
let diameter1 = xMin;
let diameter2 = xMax;
let maxSpan = xSpan;
if (ySpan > maxSpan) {
maxSpan = ySpan;
diameter1 = yMin;
diameter2 = yMax;
}
if (zSpan > maxSpan) {
maxSpan = zSpan;
diameter1 = zMin;
diameter2 = zMax;
}
// Calculate the center of the initial sphere found by Ritter's algorithm
const ritterCenter = fromPointsRitterCenter;
ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
// Calculate the radius of the initial sphere found by Ritter's algorithm
let radiusSquared = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
);
let ritterRadius = Math.sqrt(radiusSquared);
// Find the center of the sphere found using the Naive method.
const minBoxPt = fromPointsMinBoxPt;
minBoxPt.x = xMin.x;
minBoxPt.y = yMin.y;
minBoxPt.z = zMin.z;
const maxBoxPt = fromPointsMaxBoxPt;
maxBoxPt.x = xMax.x;
maxBoxPt.y = yMax.y;
maxBoxPt.z = zMax.z;
const naiveCenter = Matrix2.Cartesian3.midpoint(
minBoxPt,
maxBoxPt,
fromPointsNaiveCenterScratch
);
// Begin 2nd pass to find naive radius and modify the ritter sphere.
let naiveRadius = 0;
for (i = 0; i < numElements; i += stride) {
currentPos.x = positions[i] + center.x;
currentPos.y = positions[i + 1] + center.y;
currentPos.z = positions[i + 2] + center.z;
// Find the furthest point from the naive center to calculate the naive radius.
const r = Matrix2.Cartesian3.magnitude(
Matrix2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
);
if (r > naiveRadius) {
naiveRadius = r;
}
// Make adjustments to the Ritter Sphere to include all points.
const oldCenterToPointSquared = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
);
if (oldCenterToPointSquared > radiusSquared) {
const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
// Calculate new radius to include the point that lies outside
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
// Calculate center of new Ritter sphere
const oldToNew = oldCenterToPoint - ritterRadius;
ritterCenter.x =
(ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
oldCenterToPoint;
ritterCenter.y =
(ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
oldCenterToPoint;
ritterCenter.z =
(ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
oldCenterToPoint;
}
}
if (ritterRadius < naiveRadius) {
Matrix2.Cartesian3.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Matrix2.Cartesian3.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
/**
* Computes a tight-fitting bounding sphere enclosing a list of EncodedCartesian3s, where the points are
* stored in parallel flat arrays in X, Y, Z, order. The bounding sphere is computed by running two
* algorithms, a naive algorithm and Ritter's algorithm. The smaller of the two spheres is used to
* ensure a tight fit.
*
* @param {Number[]} [positionsHigh] An array of high bits of the encoded cartesians that the bounding sphere will enclose. Each point
* is formed from three elements in the array in the order X, Y, Z.
* @param {Number[]} [positionsLow] An array of low bits of the encoded cartesians that the bounding sphere will enclose. Each point
* is formed from three elements in the array in the order X, Y, Z.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*
* @see {@link http://blogs.agi.com/insight3d/index.php/2008/02/04/a-bounding/|Bounding Sphere computation article}
*/
BoundingSphere.fromEncodedCartesianVertices = function (
positionsHigh,
positionsLow,
result
) {
if (!when.defined(result)) {
result = new BoundingSphere();
}
if (
!when.defined(positionsHigh) ||
!when.defined(positionsLow) ||
positionsHigh.length !== positionsLow.length ||
positionsHigh.length === 0
) {
result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
const currentPos = fromPointsCurrentPos;
currentPos.x = positionsHigh[0] + positionsLow[0];
currentPos.y = positionsHigh[1] + positionsLow[1];
currentPos.z = positionsHigh[2] + positionsLow[2];
const xMin = Matrix2.Cartesian3.clone(currentPos, fromPointsXMin);
const yMin = Matrix2.Cartesian3.clone(currentPos, fromPointsYMin);
const zMin = Matrix2.Cartesian3.clone(currentPos, fromPointsZMin);
const xMax = Matrix2.Cartesian3.clone(currentPos, fromPointsXMax);
const yMax = Matrix2.Cartesian3.clone(currentPos, fromPointsYMax);
const zMax = Matrix2.Cartesian3.clone(currentPos, fromPointsZMax);
const numElements = positionsHigh.length;
let i;
for (i = 0; i < numElements; i += 3) {
const x = positionsHigh[i] + positionsLow[i];
const y = positionsHigh[i + 1] + positionsLow[i + 1];
const z = positionsHigh[i + 2] + positionsLow[i + 2];
currentPos.x = x;
currentPos.y = y;
currentPos.z = z;
// Store points containing the the smallest and largest components
if (x < xMin.x) {
Matrix2.Cartesian3.clone(currentPos, xMin);
}
if (x > xMax.x) {
Matrix2.Cartesian3.clone(currentPos, xMax);
}
if (y < yMin.y) {
Matrix2.Cartesian3.clone(currentPos, yMin);
}
if (y > yMax.y) {
Matrix2.Cartesian3.clone(currentPos, yMax);
}
if (z < zMin.z) {
Matrix2.Cartesian3.clone(currentPos, zMin);
}
if (z > zMax.z) {
Matrix2.Cartesian3.clone(currentPos, zMax);
}
}
// Compute x-, y-, and z-spans (Squared distances b/n each component's min. and max.).
const xSpan = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(xMax, xMin, fromPointsScratch)
);
const ySpan = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(yMax, yMin, fromPointsScratch)
);
const zSpan = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(zMax, zMin, fromPointsScratch)
);
// Set the diameter endpoints to the largest span.
let diameter1 = xMin;
let diameter2 = xMax;
let maxSpan = xSpan;
if (ySpan > maxSpan) {
maxSpan = ySpan;
diameter1 = yMin;
diameter2 = yMax;
}
if (zSpan > maxSpan) {
maxSpan = zSpan;
diameter1 = zMin;
diameter2 = zMax;
}
// Calculate the center of the initial sphere found by Ritter's algorithm
const ritterCenter = fromPointsRitterCenter;
ritterCenter.x = (diameter1.x + diameter2.x) * 0.5;
ritterCenter.y = (diameter1.y + diameter2.y) * 0.5;
ritterCenter.z = (diameter1.z + diameter2.z) * 0.5;
// Calculate the radius of the initial sphere found by Ritter's algorithm
let radiusSquared = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(diameter2, ritterCenter, fromPointsScratch)
);
let ritterRadius = Math.sqrt(radiusSquared);
// Find the center of the sphere found using the Naive method.
const minBoxPt = fromPointsMinBoxPt;
minBoxPt.x = xMin.x;
minBoxPt.y = yMin.y;
minBoxPt.z = zMin.z;
const maxBoxPt = fromPointsMaxBoxPt;
maxBoxPt.x = xMax.x;
maxBoxPt.y = yMax.y;
maxBoxPt.z = zMax.z;
const naiveCenter = Matrix2.Cartesian3.midpoint(
minBoxPt,
maxBoxPt,
fromPointsNaiveCenterScratch
);
// Begin 2nd pass to find naive radius and modify the ritter sphere.
let naiveRadius = 0;
for (i = 0; i < numElements; i += 3) {
currentPos.x = positionsHigh[i] + positionsLow[i];
currentPos.y = positionsHigh[i + 1] + positionsLow[i + 1];
currentPos.z = positionsHigh[i + 2] + positionsLow[i + 2];
// Find the furthest point from the naive center to calculate the naive radius.
const r = Matrix2.Cartesian3.magnitude(
Matrix2.Cartesian3.subtract(currentPos, naiveCenter, fromPointsScratch)
);
if (r > naiveRadius) {
naiveRadius = r;
}
// Make adjustments to the Ritter Sphere to include all points.
const oldCenterToPointSquared = Matrix2.Cartesian3.magnitudeSquared(
Matrix2.Cartesian3.subtract(currentPos, ritterCenter, fromPointsScratch)
);
if (oldCenterToPointSquared > radiusSquared) {
const oldCenterToPoint = Math.sqrt(oldCenterToPointSquared);
// Calculate new radius to include the point that lies outside
ritterRadius = (ritterRadius + oldCenterToPoint) * 0.5;
radiusSquared = ritterRadius * ritterRadius;
// Calculate center of new Ritter sphere
const oldToNew = oldCenterToPoint - ritterRadius;
ritterCenter.x =
(ritterRadius * ritterCenter.x + oldToNew * currentPos.x) /
oldCenterToPoint;
ritterCenter.y =
(ritterRadius * ritterCenter.y + oldToNew * currentPos.y) /
oldCenterToPoint;
ritterCenter.z =
(ritterRadius * ritterCenter.z + oldToNew * currentPos.z) /
oldCenterToPoint;
}
}
if (ritterRadius < naiveRadius) {
Matrix2.Cartesian3.clone(ritterCenter, result.center);
result.radius = ritterRadius;
} else {
Matrix2.Cartesian3.clone(naiveCenter, result.center);
result.radius = naiveRadius;
}
return result;
};
/**
* Computes a bounding sphere from the corner points of an axis-aligned bounding box. The sphere
* tighly and fully encompases the box.
*
* @param {Cartesian3} [corner] The minimum height over the rectangle.
* @param {Cartesian3} [oppositeCorner] The maximum height over the rectangle.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*
* @example
* // Create a bounding sphere around the unit cube
* const sphere = Cesium.BoundingSphere.fromCornerPoints(new Cesium.Cartesian3(-0.5, -0.5, -0.5), new Cesium.Cartesian3(0.5, 0.5, 0.5));
*/
BoundingSphere.fromCornerPoints = function (corner, oppositeCorner, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("corner", corner);
RuntimeError.Check.typeOf.object("oppositeCorner", oppositeCorner);
//>>includeEnd('debug');
if (!when.defined(result)) {
result = new BoundingSphere();
}
const center = Matrix2.Cartesian3.midpoint(corner, oppositeCorner, result.center);
result.radius = Matrix2.Cartesian3.distance(center, oppositeCorner);
return result;
};
/**
* Creates a bounding sphere encompassing an ellipsoid.
*
* @param {Ellipsoid} ellipsoid The ellipsoid around which to create a bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*
* @example
* const boundingSphere = Cesium.BoundingSphere.fromEllipsoid(ellipsoid);
*/
BoundingSphere.fromEllipsoid = function (ellipsoid, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("ellipsoid", ellipsoid);
//>>includeEnd('debug');
if (!when.defined(result)) {
result = new BoundingSphere();
}
Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
result.radius = ellipsoid.maximumRadius;
return result;
};
const fromBoundingSpheresScratch = new Matrix2.Cartesian3();
/**
* Computes a tight-fitting bounding sphere enclosing the provided array of bounding spheres.
*
* @param {BoundingSphere[]} [boundingSpheres] The array of bounding spheres.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromBoundingSpheres = function (boundingSpheres, result) {
if (!when.defined(result)) {
result = new BoundingSphere();
}
if (!when.defined(boundingSpheres) || boundingSpheres.length === 0) {
result.center = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.ZERO, result.center);
result.radius = 0.0;
return result;
}
const length = boundingSpheres.length;
if (length === 1) {
return BoundingSphere.clone(boundingSpheres[0], result);
}
if (length === 2) {
return BoundingSphere.union(boundingSpheres[0], boundingSpheres[1], result);
}
const positions = [];
let i;
for (i = 0; i < length; i++) {
positions.push(boundingSpheres[i].center);
}
result = BoundingSphere.fromPoints(positions, result);
const center = result.center;
let radius = result.radius;
for (i = 0; i < length; i++) {
const tmp = boundingSpheres[i];
radius = Math.max(
radius,
Matrix2.Cartesian3.distance(center, tmp.center, fromBoundingSpheresScratch) +
tmp.radius
);
}
result.radius = radius;
return result;
};
const fromOrientedBoundingBoxScratchU = new Matrix2.Cartesian3();
const fromOrientedBoundingBoxScratchV = new Matrix2.Cartesian3();
const fromOrientedBoundingBoxScratchW = new Matrix2.Cartesian3();
/**
* Computes a tight-fitting bounding sphere enclosing the provided oriented bounding box.
*
* @param {OrientedBoundingBox} orientedBoundingBox The oriented bounding box.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromOrientedBoundingBox = function (
orientedBoundingBox,
result
) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.defined("orientedBoundingBox", orientedBoundingBox);
//>>includeEnd('debug');
if (!when.defined(result)) {
result = new BoundingSphere();
}
const halfAxes = orientedBoundingBox.halfAxes;
const u = Matrix2.Matrix3.getColumn(halfAxes, 0, fromOrientedBoundingBoxScratchU);
const v = Matrix2.Matrix3.getColumn(halfAxes, 1, fromOrientedBoundingBoxScratchV);
const w = Matrix2.Matrix3.getColumn(halfAxes, 2, fromOrientedBoundingBoxScratchW);
Matrix2.Cartesian3.add(u, v, u);
Matrix2.Cartesian3.add(u, w, u);
result.center = Matrix2.Cartesian3.clone(orientedBoundingBox.center, result.center);
result.radius = Matrix2.Cartesian3.magnitude(u);
return result;
};
const scratchFromTransformationCenter = new Matrix2.Cartesian3();
const scratchFromTransformationScale = new Matrix2.Cartesian3();
/**
* Computes a tight-fitting bounding sphere enclosing the provided affine transformation.
*
* @param {Matrix4} transformation The affine transformation.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.fromTransformation = function (transformation, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("transformation", transformation);
//>>includeEnd('debug');
if (!when.defined(result)) {
result = new BoundingSphere();
}
const center = Matrix2.Matrix4.getTranslation(
transformation,
scratchFromTransformationCenter
);
const scale = Matrix2.Matrix4.getScale(
transformation,
scratchFromTransformationScale
);
const radius = 0.5 * Matrix2.Cartesian3.magnitude(scale);
result.center = Matrix2.Cartesian3.clone(center, result.center);
result.radius = radius;
return result;
};
/**
* Duplicates a BoundingSphere instance.
*
* @param {BoundingSphere} sphere The bounding sphere to duplicate.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided. (Returns undefined if sphere is undefined)
*/
BoundingSphere.clone = function (sphere, result) {
if (!when.defined(sphere)) {
return undefined;
}
if (!when.defined(result)) {
return new BoundingSphere(sphere.center, sphere.radius);
}
result.center = Matrix2.Cartesian3.clone(sphere.center, result.center);
result.radius = sphere.radius;
return result;
};
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
BoundingSphere.packedLength = 4;
/**
* Stores the provided instance into the provided array.
*
* @param {BoundingSphere} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {Number[]} The array that was packed into
*/
BoundingSphere.pack = function (value, array, startingIndex) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("value", value);
RuntimeError.Check.defined("array", array);
//>>includeEnd('debug');
startingIndex = when.defaultValue(startingIndex, 0);
const center = value.center;
array[startingIndex++] = center.x;
array[startingIndex++] = center.y;
array[startingIndex++] = center.z;
array[startingIndex] = value.radius;
return array;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {BoundingSphere} [result] The object into which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if one was not provided.
*/
BoundingSphere.unpack = function (array, startingIndex, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.defined("array", array);
//>>includeEnd('debug');
startingIndex = when.defaultValue(startingIndex, 0);
if (!when.defined(result)) {
result = new BoundingSphere();
}
const center = result.center;
center.x = array[startingIndex++];
center.y = array[startingIndex++];
center.z = array[startingIndex++];
result.radius = array[startingIndex];
return result;
};
const unionScratch = new Matrix2.Cartesian3();
const unionScratchCenter = new Matrix2.Cartesian3();
/**
* Computes a bounding sphere that contains both the left and right bounding spheres.
*
* @param {BoundingSphere} left A sphere to enclose in a bounding sphere.
* @param {BoundingSphere} right A sphere to enclose in a bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.union = function (left, right, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("left", left);
RuntimeError.Check.typeOf.object("right", right);
//>>includeEnd('debug');
if (!when.defined(result)) {
result = new BoundingSphere();
}
const leftCenter = left.center;
const leftRadius = left.radius;
const rightCenter = right.center;
const rightRadius = right.radius;
const toRightCenter = Matrix2.Cartesian3.subtract(
rightCenter,
leftCenter,
unionScratch
);
const centerSeparation = Matrix2.Cartesian3.magnitude(toRightCenter);
if (leftRadius >= centerSeparation + rightRadius) {
// Left sphere wins.
left.clone(result);
return result;
}
if (rightRadius >= centerSeparation + leftRadius) {
// Right sphere wins.
right.clone(result);
return result;
}
// There are two tangent points, one on far side of each sphere.
const halfDistanceBetweenTangentPoints =
(leftRadius + centerSeparation + rightRadius) * 0.5;
// Compute the center point halfway between the two tangent points.
const center = Matrix2.Cartesian3.multiplyByScalar(
toRightCenter,
(-leftRadius + halfDistanceBetweenTangentPoints) / centerSeparation,
unionScratchCenter
);
Matrix2.Cartesian3.add(center, leftCenter, center);
Matrix2.Cartesian3.clone(center, result.center);
result.radius = halfDistanceBetweenTangentPoints;
return result;
};
const expandScratch = new Matrix2.Cartesian3();
/**
* Computes a bounding sphere by enlarging the provided sphere to contain the provided point.
*
* @param {BoundingSphere} sphere A sphere to expand.
* @param {Cartesian3} point A point to enclose in a bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.expand = function (sphere, point, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("sphere", sphere);
RuntimeError.Check.typeOf.object("point", point);
//>>includeEnd('debug');
result = BoundingSphere.clone(sphere, result);
const radius = Matrix2.Cartesian3.magnitude(
Matrix2.Cartesian3.subtract(point, result.center, expandScratch)
);
if (radius > result.radius) {
result.radius = radius;
}
return result;
};
/**
* Determines which side of a plane a sphere is located.
*
* @param {BoundingSphere} sphere The bounding sphere to test.
* @param {Plane} plane The plane to test against.
* @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
* the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
* on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
* intersects the plane.
*/
BoundingSphere.intersectPlane = function (sphere, plane) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("sphere", sphere);
RuntimeError.Check.typeOf.object("plane", plane);
//>>includeEnd('debug');
const center = sphere.center;
const radius = sphere.radius;
const normal = plane.normal;
const distanceToPlane = Matrix2.Cartesian3.dot(normal, center) + plane.distance;
if (distanceToPlane < -radius) {
// The center point is negative side of the plane normal
return Intersect$1.OUTSIDE;
} else if (distanceToPlane < radius) {
// The center point is positive side of the plane, but radius extends beyond it; partial overlap
return Intersect$1.INTERSECTING;
}
return Intersect$1.INSIDE;
};
/**
* Applies a 4x4 affine transformation matrix to a bounding sphere.
*
* @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
* @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.transform = function (sphere, transform, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("sphere", sphere);
RuntimeError.Check.typeOf.object("transform", transform);
//>>includeEnd('debug');
if (!when.defined(result)) {
result = new BoundingSphere();
}
result.center = Matrix2.Matrix4.multiplyByPoint(
transform,
sphere.center,
result.center
);
result.radius = Matrix2.Matrix4.getMaximumScale(transform) * sphere.radius;
return result;
};
const distanceSquaredToScratch = new Matrix2.Cartesian3();
/**
* Computes the estimated distance squared from the closest point on a bounding sphere to a point.
*
* @param {BoundingSphere} sphere The sphere.
* @param {Cartesian3} cartesian The point
* @returns {Number} The distance squared from the bounding sphere to the point. Returns 0 if the point is inside the sphere.
*
* @example
* // Sort bounding spheres from back to front
* spheres.sort(function(a, b) {
* return Cesium.BoundingSphere.distanceSquaredTo(b, camera.positionWC) - Cesium.BoundingSphere.distanceSquaredTo(a, camera.positionWC);
* });
*/
BoundingSphere.distanceSquaredTo = function (sphere, cartesian) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("sphere", sphere);
RuntimeError.Check.typeOf.object("cartesian", cartesian);
//>>includeEnd('debug');
const diff = Matrix2.Cartesian3.subtract(
sphere.center,
cartesian,
distanceSquaredToScratch
);
const distance = Matrix2.Cartesian3.magnitude(diff) - sphere.radius;
if (distance <= 0.0) {
return 0.0;
}
return distance * distance;
};
/**
* Applies a 4x4 affine transformation matrix to a bounding sphere where there is no scale
* The transformation matrix is not verified to have a uniform scale of 1.
* This method is faster than computing the general bounding sphere transform using {@link BoundingSphere.transform}.
*
* @param {BoundingSphere} sphere The bounding sphere to apply the transformation to.
* @param {Matrix4} transform The transformation matrix to apply to the bounding sphere.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*
* @example
* const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positionOnEllipsoid);
* const boundingSphere = new Cesium.BoundingSphere();
* const newBoundingSphere = Cesium.BoundingSphere.transformWithoutScale(boundingSphere, modelMatrix);
*/
BoundingSphere.transformWithoutScale = function (sphere, transform, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("sphere", sphere);
RuntimeError.Check.typeOf.object("transform", transform);
//>>includeEnd('debug');
if (!when.defined(result)) {
result = new BoundingSphere();
}
result.center = Matrix2.Matrix4.multiplyByPoint(
transform,
sphere.center,
result.center
);
result.radius = sphere.radius;
return result;
};
const scratchCartesian3 = new Matrix2.Cartesian3();
/**
* The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
* plus/minus the radius of the bounding sphere.
*
* If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
* closest and farthest planes from position that intersect the bounding sphere.
*
* @param {BoundingSphere} sphere The bounding sphere to calculate the distance to.
* @param {Cartesian3} position The position to calculate the distance from.
* @param {Cartesian3} direction The direction from position.
* @param {Interval} [result] A Interval to store the nearest and farthest distances.
* @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
*/
BoundingSphere.computePlaneDistances = function (
sphere,
position,
direction,
result
) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("sphere", sphere);
RuntimeError.Check.typeOf.object("position", position);
RuntimeError.Check.typeOf.object("direction", direction);
//>>includeEnd('debug');
if (!when.defined(result)) {
result = new Interval();
}
const toCenter = Matrix2.Cartesian3.subtract(
sphere.center,
position,
scratchCartesian3
);
const mag = Matrix2.Cartesian3.dot(direction, toCenter);
result.start = mag - sphere.radius;
result.stop = mag + sphere.radius;
return result;
};
const projectTo2DNormalScratch = new Matrix2.Cartesian3();
const projectTo2DEastScratch = new Matrix2.Cartesian3();
const projectTo2DNorthScratch = new Matrix2.Cartesian3();
const projectTo2DWestScratch = new Matrix2.Cartesian3();
const projectTo2DSouthScratch = new Matrix2.Cartesian3();
const projectTo2DCartographicScratch = new Matrix2.Cartographic();
const projectTo2DPositionsScratch = new Array(8);
for (let n = 0; n < 8; ++n) {
projectTo2DPositionsScratch[n] = new Matrix2.Cartesian3();
}
const projectTo2DProjection = new GeographicProjection();
/**
* Creates a bounding sphere in 2D from a bounding sphere in 3D world coordinates.
*
* @param {BoundingSphere} sphere The bounding sphere to transform to 2D.
* @param {Object} [projection=GeographicProjection] The projection to 2D.
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.projectTo2D = function (sphere, projection, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("sphere", sphere);
//>>includeEnd('debug');
projection = when.defaultValue(projection, projectTo2DProjection);
const ellipsoid = projection.ellipsoid;
let center = sphere.center;
const radius = sphere.radius;
let normal;
if (Matrix2.Cartesian3.equals(center, Matrix2.Cartesian3.ZERO)) {
// Bounding sphere is at the center. The geodetic surface normal is not
// defined here so pick the x-axis as a fallback.
normal = Matrix2.Cartesian3.clone(Matrix2.Cartesian3.UNIT_X, projectTo2DNormalScratch);
} else {
normal = ellipsoid.geodeticSurfaceNormal(center, projectTo2DNormalScratch);
}
const east = Matrix2.Cartesian3.cross(
Matrix2.Cartesian3.UNIT_Z,
normal,
projectTo2DEastScratch
);
Matrix2.Cartesian3.normalize(east, east);
const north = Matrix2.Cartesian3.cross(normal, east, projectTo2DNorthScratch);
Matrix2.Cartesian3.normalize(north, north);
Matrix2.Cartesian3.multiplyByScalar(normal, radius, normal);
Matrix2.Cartesian3.multiplyByScalar(north, radius, north);
Matrix2.Cartesian3.multiplyByScalar(east, radius, east);
const south = Matrix2.Cartesian3.negate(north, projectTo2DSouthScratch);
const west = Matrix2.Cartesian3.negate(east, projectTo2DWestScratch);
const positions = projectTo2DPositionsScratch;
// top NE corner
let corner = positions[0];
Matrix2.Cartesian3.add(normal, north, corner);
Matrix2.Cartesian3.add(corner, east, corner);
// top NW corner
corner = positions[1];
Matrix2.Cartesian3.add(normal, north, corner);
Matrix2.Cartesian3.add(corner, west, corner);
// top SW corner
corner = positions[2];
Matrix2.Cartesian3.add(normal, south, corner);
Matrix2.Cartesian3.add(corner, west, corner);
// top SE corner
corner = positions[3];
Matrix2.Cartesian3.add(normal, south, corner);
Matrix2.Cartesian3.add(corner, east, corner);
Matrix2.Cartesian3.negate(normal, normal);
// bottom NE corner
corner = positions[4];
Matrix2.Cartesian3.add(normal, north, corner);
Matrix2.Cartesian3.add(corner, east, corner);
// bottom NW corner
corner = positions[5];
Matrix2.Cartesian3.add(normal, north, corner);
Matrix2.Cartesian3.add(corner, west, corner);
// bottom SW corner
corner = positions[6];
Matrix2.Cartesian3.add(normal, south, corner);
Matrix2.Cartesian3.add(corner, west, corner);
// bottom SE corner
corner = positions[7];
Matrix2.Cartesian3.add(normal, south, corner);
Matrix2.Cartesian3.add(corner, east, corner);
const length = positions.length;
for (let i = 0; i < length; ++i) {
const position = positions[i];
Matrix2.Cartesian3.add(center, position, position);
const cartographic = ellipsoid.cartesianToCartographic(
position,
projectTo2DCartographicScratch
);
projection.project(cartographic, position);
}
result = BoundingSphere.fromPoints(positions, result);
// swizzle center components
center = result.center;
const x = center.x;
const y = center.y;
const z = center.z;
center.x = z;
center.y = x;
center.z = y;
return result;
};
/**
* Determines whether or not a sphere is hidden from view by the occluder.
*
* @param {BoundingSphere} sphere The bounding sphere surrounding the occludee object.
* @param {Occluder} occluder The occluder.
* @returns {Boolean} true
if the sphere is not visible; otherwise false
.
*/
BoundingSphere.isOccluded = function (sphere, occluder) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("sphere", sphere);
RuntimeError.Check.typeOf.object("occluder", occluder);
//>>includeEnd('debug');
return !occluder.isBoundingSphereVisible(sphere);
};
/**
* Compares the provided BoundingSphere componentwise and returns
* true
if they are equal, false
otherwise.
*
* @param {BoundingSphere} [left] The first BoundingSphere.
* @param {BoundingSphere} [right] The second BoundingSphere.
* @returns {Boolean} true
if left and right are equal, false
otherwise.
*/
BoundingSphere.equals = function (left, right) {
return (
left === right ||
(when.defined(left) &&
when.defined(right) &&
Matrix2.Cartesian3.equals(left.center, right.center) &&
left.radius === right.radius)
);
};
/**
* Determines which side of a plane the sphere is located.
*
* @param {Plane} plane The plane to test against.
* @returns {Intersect} {@link Intersect.INSIDE} if the entire sphere is on the side of the plane
* the normal is pointing, {@link Intersect.OUTSIDE} if the entire sphere is
* on the opposite side, and {@link Intersect.INTERSECTING} if the sphere
* intersects the plane.
*/
BoundingSphere.prototype.intersectPlane = function (plane) {
return BoundingSphere.intersectPlane(this, plane);
};
/**
* Computes the estimated distance squared from the closest point on a bounding sphere to a point.
*
* @param {Cartesian3} cartesian The point
* @returns {Number} The estimated distance squared from the bounding sphere to the point.
*
* @example
* // Sort bounding spheres from back to front
* spheres.sort(function(a, b) {
* return b.distanceSquaredTo(camera.positionWC) - a.distanceSquaredTo(camera.positionWC);
* });
*/
BoundingSphere.prototype.distanceSquaredTo = function (cartesian) {
return BoundingSphere.distanceSquaredTo(this, cartesian);
};
/**
* The distances calculated by the vector from the center of the bounding sphere to position projected onto direction
* plus/minus the radius of the bounding sphere.
*
* If you imagine the infinite number of planes with normal direction, this computes the smallest distance to the
* closest and farthest planes from position that intersect the bounding sphere.
*
* @param {Cartesian3} position The position to calculate the distance from.
* @param {Cartesian3} direction The direction from position.
* @param {Interval} [result] A Interval to store the nearest and farthest distances.
* @returns {Interval} The nearest and farthest distances on the bounding sphere from position in direction.
*/
BoundingSphere.prototype.computePlaneDistances = function (
position,
direction,
result
) {
return BoundingSphere.computePlaneDistances(
this,
position,
direction,
result
);
};
/**
* Determines whether or not a sphere is hidden from view by the occluder.
*
* @param {Occluder} occluder The occluder.
* @returns {Boolean} true
if the sphere is not visible; otherwise false
.
*/
BoundingSphere.prototype.isOccluded = function (occluder) {
return BoundingSphere.isOccluded(this, occluder);
};
/**
* Compares this BoundingSphere against the provided BoundingSphere componentwise and returns
* true
if they are equal, false
otherwise.
*
* @param {BoundingSphere} [right] The right hand side BoundingSphere.
* @returns {Boolean} true
if they are equal, false
otherwise.
*/
BoundingSphere.prototype.equals = function (right) {
return BoundingSphere.equals(this, right);
};
/**
* Duplicates this BoundingSphere instance.
*
* @param {BoundingSphere} [result] The object onto which to store the result.
* @returns {BoundingSphere} The modified result parameter or a new BoundingSphere instance if none was provided.
*/
BoundingSphere.prototype.clone = function (result) {
return BoundingSphere.clone(this, result);
};
/**
* Computes the radius of the BoundingSphere.
* @returns {Number} The radius of the BoundingSphere.
*/
BoundingSphere.prototype.volume = function () {
const radius = this.radius;
return volumeConstant * radius * radius * radius;
};
let _supportsFullscreen;
const _names = {
requestFullscreen: undefined,
exitFullscreen: undefined,
fullscreenEnabled: undefined,
fullscreenElement: undefined,
fullscreenchange: undefined,
fullscreenerror: undefined,
};
/**
* Browser-independent functions for working with the standard fullscreen API.
*
* @namespace Fullscreen
*
* @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
*/
const Fullscreen = {};
Object.defineProperties(Fullscreen, {
/**
* The element that is currently fullscreen, if any. To simply check if the
* browser is in fullscreen mode or not, use {@link Fullscreen#fullscreen}.
* @memberof Fullscreen
* @type {Object}
* @readonly
*/
element: {
get: function () {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return document[_names.fullscreenElement];
},
},
/**
* The name of the event on the document that is fired when fullscreen is
* entered or exited. This event name is intended for use with addEventListener.
* In your event handler, to determine if the browser is in fullscreen mode or not,
* use {@link Fullscreen#fullscreen}.
* @memberof Fullscreen
* @type {String}
* @readonly
*/
changeEventName: {
get: function () {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return _names.fullscreenchange;
},
},
/**
* The name of the event that is fired when a fullscreen error
* occurs. This event name is intended for use with addEventListener.
* @memberof Fullscreen
* @type {String}
* @readonly
*/
errorEventName: {
get: function () {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return _names.fullscreenerror;
},
},
/**
* Determine whether the browser will allow an element to be made fullscreen, or not.
* For example, by default, iframes cannot go fullscreen unless the containing page
* adds an "allowfullscreen" attribute (or prefixed equivalent).
* @memberof Fullscreen
* @type {Boolean}
* @readonly
*/
enabled: {
get: function () {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return document[_names.fullscreenEnabled];
},
},
/**
* Determines if the browser is currently in fullscreen mode.
* @memberof Fullscreen
* @type {Boolean}
* @readonly
*/
fullscreen: {
get: function () {
if (!Fullscreen.supportsFullscreen()) {
return undefined;
}
return Fullscreen.element !== null;
},
},
});
/**
* Detects whether the browser supports the standard fullscreen API.
*
* @returns {Boolean} true
if the browser supports the standard fullscreen API,
* false
otherwise.
*/
Fullscreen.supportsFullscreen = function () {
if (when.defined(_supportsFullscreen)) {
return _supportsFullscreen;
}
_supportsFullscreen = false;
const body = document.body;
if (typeof body.requestFullscreen === "function") {
// go with the unprefixed, standard set of names
_names.requestFullscreen = "requestFullscreen";
_names.exitFullscreen = "exitFullscreen";
_names.fullscreenEnabled = "fullscreenEnabled";
_names.fullscreenElement = "fullscreenElement";
_names.fullscreenchange = "fullscreenchange";
_names.fullscreenerror = "fullscreenerror";
_supportsFullscreen = true;
return _supportsFullscreen;
}
//check for the correct combination of prefix plus the various names that browsers use
const prefixes = ["webkit", "moz", "o", "ms", "khtml"];
let name;
for (let i = 0, len = prefixes.length; i < len; ++i) {
const prefix = prefixes[i];
// casing of Fullscreen differs across browsers
name = `${prefix}RequestFullscreen`;
if (typeof body[name] === "function") {
_names.requestFullscreen = name;
_supportsFullscreen = true;
} else {
name = `${prefix}RequestFullScreen`;
if (typeof body[name] === "function") {
_names.requestFullscreen = name;
_supportsFullscreen = true;
}
}
// disagreement about whether it's "exit" as per spec, or "cancel"
name = `${prefix}ExitFullscreen`;
if (typeof document[name] === "function") {
_names.exitFullscreen = name;
} else {
name = `${prefix}CancelFullScreen`;
if (typeof document[name] === "function") {
_names.exitFullscreen = name;
}
}
// casing of Fullscreen differs across browsers
name = `${prefix}FullscreenEnabled`;
if (document[name] !== undefined) {
_names.fullscreenEnabled = name;
} else {
name = `${prefix}FullScreenEnabled`;
if (document[name] !== undefined) {
_names.fullscreenEnabled = name;
}
}
// casing of Fullscreen differs across browsers
name = `${prefix}FullscreenElement`;
if (document[name] !== undefined) {
_names.fullscreenElement = name;
} else {
name = `${prefix}FullScreenElement`;
if (document[name] !== undefined) {
_names.fullscreenElement = name;
}
}
// thankfully, event names are all lowercase per spec
name = `${prefix}fullscreenchange`;
// event names do not have 'on' in the front, but the property on the document does
if (document[`on${name}`] !== undefined) {
//except on IE
if (prefix === "ms") {
name = "MSFullscreenChange";
}
_names.fullscreenchange = name;
}
name = `${prefix}fullscreenerror`;
if (document[`on${name}`] !== undefined) {
//except on IE
if (prefix === "ms") {
name = "MSFullscreenError";
}
_names.fullscreenerror = name;
}
}
return _supportsFullscreen;
};
/**
* Asynchronously requests the browser to enter fullscreen mode on the given element.
* If fullscreen mode is not supported by the browser, does nothing.
*
* @param {Object} element The HTML element which will be placed into fullscreen mode.
* @param {Object} [vrDevice] The HMDVRDevice device.
*
* @example
* // Put the entire page into fullscreen.
* Cesium.Fullscreen.requestFullscreen(document.body)
*
* // Place only the Cesium canvas into fullscreen.
* Cesium.Fullscreen.requestFullscreen(scene.canvas)
*/
Fullscreen.requestFullscreen = function (element, vrDevice) {
if (!Fullscreen.supportsFullscreen()) {
return;
}
element[_names.requestFullscreen]({ vrDisplay: vrDevice });
};
/**
* Asynchronously exits fullscreen mode. If the browser is not currently
* in fullscreen, or if fullscreen mode is not supported by the browser, does nothing.
*/
Fullscreen.exitFullscreen = function () {
if (!Fullscreen.supportsFullscreen()) {
return;
}
document[_names.exitFullscreen]();
};
//For unit tests
Fullscreen._names = _names;
let theNavigator;
if (typeof navigator !== "undefined") {
theNavigator = navigator;
} else {
theNavigator = {};
}
function extractVersion(versionString) {
const parts = versionString.split(".");
for (let i = 0, len = parts.length; i < len; ++i) {
parts[i] = parseInt(parts[i], 10);
}
return parts;
}
let isChromeResult;
let chromeVersionResult;
function isChrome() {
if (!when.defined(isChromeResult)) {
isChromeResult = false;
// Edge contains Chrome in the user agent too
if (!isEdge()) {
const fields = / Chrome\/([\.0-9]+)/.exec(theNavigator.userAgent);
if (fields !== null) {
isChromeResult = true;
chromeVersionResult = extractVersion(fields[1]);
}
}
}
return isChromeResult;
}
function chromeVersion() {
return isChrome() && chromeVersionResult;
}
let isSafariResult;
let safariVersionResult;
function isSafari() {
if (!when.defined(isSafariResult)) {
isSafariResult = false;
// Chrome and Edge contain Safari in the user agent too
if (
!isChrome() &&
!isEdge() &&
/ Safari\/[\.0-9]+/.test(theNavigator.userAgent)
) {
const fields = / Version\/([\.0-9]+)/.exec(theNavigator.userAgent);
if (fields !== null) {
isSafariResult = true;
safariVersionResult = extractVersion(fields[1]);
}
}
}
return isSafariResult;
}
function safariVersion() {
return isSafari() && safariVersionResult;
}
let isWebkitResult;
let webkitVersionResult;
function isWebkit() {
if (!when.defined(isWebkitResult)) {
isWebkitResult = false;
const fields = / AppleWebKit\/([\.0-9]+)(\+?)/.exec(theNavigator.userAgent);
if (fields !== null) {
isWebkitResult = true;
webkitVersionResult = extractVersion(fields[1]);
webkitVersionResult.isNightly = !!fields[2];
}
}
return isWebkitResult;
}
function webkitVersion() {
return isWebkit() && webkitVersionResult;
}
let isInternetExplorerResult;
let internetExplorerVersionResult;
function isInternetExplorer() {
if (!when.defined(isInternetExplorerResult)) {
isInternetExplorerResult = false;
let fields;
if (theNavigator.appName === "Microsoft Internet Explorer") {
fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent);
if (fields !== null) {
isInternetExplorerResult = true;
internetExplorerVersionResult = extractVersion(fields[1]);
}
} else if (theNavigator.appName === "Netscape") {
fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(
theNavigator.userAgent
);
if (fields !== null) {
isInternetExplorerResult = true;
internetExplorerVersionResult = extractVersion(fields[1]);
}
}
}
return isInternetExplorerResult;
}
function internetExplorerVersion() {
return isInternetExplorer() && internetExplorerVersionResult;
}
let isEdgeResult;
let edgeVersionResult;
function isEdge() {
if (!when.defined(isEdgeResult)) {
isEdgeResult = false;
const fields = / Edge\/([\.0-9]+)/.exec(theNavigator.userAgent);
if (fields !== null) {
isEdgeResult = true;
edgeVersionResult = extractVersion(fields[1]);
}
}
return isEdgeResult;
}
function edgeVersion() {
return isEdge() && edgeVersionResult;
}
let isFirefoxResult;
let firefoxVersionResult;
function isFirefox() {
if (!when.defined(isFirefoxResult)) {
isFirefoxResult = false;
const fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent);
if (fields !== null) {
isFirefoxResult = true;
firefoxVersionResult = extractVersion(fields[1]);
}
}
return isFirefoxResult;
}
let isWindowsResult;
function isWindows() {
if (!when.defined(isWindowsResult)) {
isWindowsResult = /Windows/i.test(theNavigator.appVersion);
}
return isWindowsResult;
}
function firefoxVersion() {
return isFirefox() && firefoxVersionResult;
}
let hasPointerEvents;
function supportsPointerEvents() {
if (!when.defined(hasPointerEvents)) {
//While navigator.pointerEnabled is deprecated in the W3C specification
//we still need to use it if it exists in order to support browsers
//that rely on it, such as the Windows WebBrowser control which defines
//PointerEvent but sets navigator.pointerEnabled to false.
//Firefox disabled because of https://github.com/CesiumGS/cesium/issues/6372
hasPointerEvents =
!isFirefox() &&
typeof PointerEvent !== "undefined" &&
(!when.defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled);
}
return hasPointerEvents;
}
let imageRenderingValueResult;
let supportsImageRenderingPixelatedResult;
function supportsImageRenderingPixelated() {
if (!when.defined(supportsImageRenderingPixelatedResult)) {
const canvas = document.createElement("canvas");
canvas.setAttribute(
"style",
"image-rendering: -moz-crisp-edges;" + "image-rendering: pixelated;"
);
//canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers.
const tmp = canvas.style.imageRendering;
supportsImageRenderingPixelatedResult = when.defined(tmp) && tmp !== "";
if (supportsImageRenderingPixelatedResult) {
imageRenderingValueResult = tmp;
}
}
return supportsImageRenderingPixelatedResult;
}
function imageRenderingValue() {
return supportsImageRenderingPixelated()
? imageRenderingValueResult
: undefined;
}
function supportsWebP() {
//>>includeStart('debug', pragmas.debug);
if (!supportsWebP.initialized) {
throw new RuntimeError.DeveloperError(
"You must call FeatureDetection.supportsWebP.initialize and wait for the promise to resolve before calling FeatureDetection.supportsWebP"
);
}
//>>includeEnd('debug');
return supportsWebP._result;
}
supportsWebP._promise = undefined;
supportsWebP._result = undefined;
supportsWebP.initialize = function () {
// From https://developers.google.com/speed/webp/faq#how_can_i_detect_browser_support_for_webp
if (when.defined(supportsWebP._promise)) {
return supportsWebP._promise;
}
const supportsWebPDeferred = when.when.defer();
supportsWebP._promise = supportsWebPDeferred.promise;
if (isEdge()) {
// Edge's WebP support with WebGL is incomplete.
// See bug report: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/19221241/
supportsWebP._result = false;
supportsWebPDeferred.resolve(supportsWebP._result);
return supportsWebPDeferred.promise;
}
const image = new Image();
image.onload = function () {
supportsWebP._result = image.width > 0 && image.height > 0;
supportsWebPDeferred.resolve(supportsWebP._result);
};
image.onerror = function () {
supportsWebP._result = false;
supportsWebPDeferred.resolve(supportsWebP._result);
};
image.src =
"data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA";
return supportsWebPDeferred.promise;
};
Object.defineProperties(supportsWebP, {
initialized: {
get: function () {
return when.defined(supportsWebP._result);
},
},
});
const typedArrayTypes = [];
if (typeof ArrayBuffer !== "undefined") {
typedArrayTypes.push(
Int8Array,
Uint8Array,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array,
Float64Array
);
if (typeof Uint8ClampedArray !== "undefined") {
typedArrayTypes.push(Uint8ClampedArray);
}
if (typeof Uint8ClampedArray !== "undefined") {
typedArrayTypes.push(Uint8ClampedArray);
}
if (typeof BigInt64Array !== "undefined") {
// eslint-disable-next-line no-undef
typedArrayTypes.push(BigInt64Array);
}
if (typeof BigUint64Array !== "undefined") {
// eslint-disable-next-line no-undef
typedArrayTypes.push(BigUint64Array);
}
}
/**
* A set of functions to detect whether the current browser supports
* various features.
*
* @namespace FeatureDetection
*/
const FeatureDetection = {
isChrome: isChrome,
chromeVersion: chromeVersion,
isSafari: isSafari,
safariVersion: safariVersion,
isWebkit: isWebkit,
webkitVersion: webkitVersion,
isInternetExplorer: isInternetExplorer,
internetExplorerVersion: internetExplorerVersion,
isEdge: isEdge,
edgeVersion: edgeVersion,
isFirefox: isFirefox,
firefoxVersion: firefoxVersion,
isWindows: isWindows,
hardwareConcurrency: when.defaultValue(theNavigator.hardwareConcurrency, 3),
supportsPointerEvents: supportsPointerEvents,
supportsImageRenderingPixelated: supportsImageRenderingPixelated,
supportsWebP: supportsWebP,
imageRenderingValue: imageRenderingValue,
typedArrayTypes: typedArrayTypes,
};
/**
* Detects whether the current browser supports Basis Universal textures and the web assembly modules needed to transcode them.
*
* @param {Scene} scene
* @returns {Boolean} true if the browser supports web assembly modules and the scene supports Basis Universal textures, false if not.
*/
FeatureDetection.supportsBasis = function (scene) {
return FeatureDetection.supportsWebAssembly() && scene.context.supportsBasis;
};
/**
* Detects whether the current browser supports the full screen standard.
*
* @returns {Boolean} true if the browser supports the full screen standard, false if not.
*
* @see Fullscreen
* @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification}
*/
FeatureDetection.supportsFullscreen = function () {
return Fullscreen.supportsFullscreen();
};
/**
* Detects whether the current browser supports typed arrays.
*
* @returns {Boolean} true if the browser supports typed arrays, false if not.
*
* @see {@link https://tc39.es/ecma262/#sec-typedarray-objects|Typed Array Specification}
*/
FeatureDetection.supportsTypedArrays = function () {
return typeof ArrayBuffer !== "undefined";
};
/**
* Detects whether the current browser supports BigInt64Array typed arrays.
*
* @returns {Boolean} true if the browser supports BigInt64Array typed arrays, false if not.
*
* @see {@link https://tc39.es/ecma262/#sec-typedarray-objects|Typed Array Specification}
*/
FeatureDetection.supportsBigInt64Array = function () {
return typeof BigInt64Array !== "undefined";
};
/**
* Detects whether the current browser supports BigUint64Array typed arrays.
*
* @returns {Boolean} true if the browser supports BigUint64Array typed arrays, false if not.
*
* @see {@link https://tc39.es/ecma262/#sec-typedarray-objects|Typed Array Specification}
*/
FeatureDetection.supportsBigUint64Array = function () {
return typeof BigUint64Array !== "undefined";
};
/**
* Detects whether the current browser supports BigInt.
*
* @returns {Boolean} true if the browser supports BigInt, false if not.
*
* @see {@link https://tc39.es/ecma262/#sec-bigint-objects|BigInt Specification}
*/
FeatureDetection.supportsBigInt = function () {
return typeof BigInt !== "undefined";
};
/**
* Detects whether the current browser supports Web Workers.
*
* @returns {Boolean} true if the browsers supports Web Workers, false if not.
*
* @see {@link http://www.w3.org/TR/workers/}
*/
FeatureDetection.supportsWebWorkers = function () {
return typeof Worker !== "undefined";
};
/**
* Detects whether the current browser supports Web Assembly.
*
* @returns {Boolean} true if the browsers supports Web Assembly, false if not.
*
* @see {@link https://developer.mozilla.org/en-US/docs/WebAssembly}
*/
FeatureDetection.supportsWebAssembly = function () {
return typeof WebAssembly !== "undefined" && !FeatureDetection.isEdge();
};
/**
* A set of 4-dimensional coordinates used to represent rotation in 3-dimensional space.
* @alias Quaternion
* @constructor
*
* @param {Number} [x=0.0] The X component.
* @param {Number} [y=0.0] The Y component.
* @param {Number} [z=0.0] The Z component.
* @param {Number} [w=0.0] The W component.
*
* @see PackableForInterpolation
*/
function Quaternion(x, y, z, w) {
/**
* The X component.
* @type {Number}
* @default 0.0
*/
this.x = when.defaultValue(x, 0.0);
/**
* The Y component.
* @type {Number}
* @default 0.0
*/
this.y = when.defaultValue(y, 0.0);
/**
* The Z component.
* @type {Number}
* @default 0.0
*/
this.z = when.defaultValue(z, 0.0);
/**
* The W component.
* @type {Number}
* @default 0.0
*/
this.w = when.defaultValue(w, 0.0);
}
let fromAxisAngleScratch = new Matrix2.Cartesian3();
/**
* Computes a quaternion representing a rotation around an axis.
*
* @param {Cartesian3} axis The axis of rotation.
* @param {Number} angle The angle in radians to rotate around the axis.
* @param {Quaternion} [result] The object onto which to store the result.
* @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
*/
Quaternion.fromAxisAngle = function (axis, angle, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("axis", axis);
RuntimeError.Check.typeOf.number("angle", angle);
//>>includeEnd('debug');
const halfAngle = angle / 2.0;
const s = Math.sin(halfAngle);
fromAxisAngleScratch = Matrix2.Cartesian3.normalize(axis, fromAxisAngleScratch);
const x = fromAxisAngleScratch.x * s;
const y = fromAxisAngleScratch.y * s;
const z = fromAxisAngleScratch.z * s;
const w = Math.cos(halfAngle);
if (!when.defined(result)) {
return new Quaternion(x, y, z, w);
}
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
const fromRotationMatrixNext = [1, 2, 0];
const fromRotationMatrixQuat = new Array(3);
/**
* Computes a Quaternion from the provided Matrix3 instance.
*
* @param {Matrix3} matrix The rotation matrix.
* @param {Quaternion} [result] The object onto which to store the result.
* @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
*
* @see Matrix3.fromQuaternion
*/
Quaternion.fromRotationMatrix = function (matrix, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("matrix", matrix);
//>>includeEnd('debug');
let root;
let x;
let y;
let z;
let w;
const m00 = matrix[Matrix2.Matrix3.COLUMN0ROW0];
const m11 = matrix[Matrix2.Matrix3.COLUMN1ROW1];
const m22 = matrix[Matrix2.Matrix3.COLUMN2ROW2];
const trace = m00 + m11 + m22;
if (trace > 0.0) {
// |w| > 1/2, may as well choose w > 1/2
root = Math.sqrt(trace + 1.0); // 2w
w = 0.5 * root;
root = 0.5 / root; // 1/(4w)
x = (matrix[Matrix2.Matrix3.COLUMN1ROW2] - matrix[Matrix2.Matrix3.COLUMN2ROW1]) * root;
y = (matrix[Matrix2.Matrix3.COLUMN2ROW0] - matrix[Matrix2.Matrix3.COLUMN0ROW2]) * root;
z = (matrix[Matrix2.Matrix3.COLUMN0ROW1] - matrix[Matrix2.Matrix3.COLUMN1ROW0]) * root;
} else {
// |w| <= 1/2
const next = fromRotationMatrixNext;
let i = 0;
if (m11 > m00) {
i = 1;
}
if (m22 > m00 && m22 > m11) {
i = 2;
}
const j = next[i];
const k = next[j];
root = Math.sqrt(
matrix[Matrix2.Matrix3.getElementIndex(i, i)] -
matrix[Matrix2.Matrix3.getElementIndex(j, j)] -
matrix[Matrix2.Matrix3.getElementIndex(k, k)] +
1.0
);
const quat = fromRotationMatrixQuat;
quat[i] = 0.5 * root;
root = 0.5 / root;
w =
(matrix[Matrix2.Matrix3.getElementIndex(k, j)] -
matrix[Matrix2.Matrix3.getElementIndex(j, k)]) *
root;
quat[j] =
(matrix[Matrix2.Matrix3.getElementIndex(j, i)] +
matrix[Matrix2.Matrix3.getElementIndex(i, j)]) *
root;
quat[k] =
(matrix[Matrix2.Matrix3.getElementIndex(k, i)] +
matrix[Matrix2.Matrix3.getElementIndex(i, k)]) *
root;
x = -quat[0];
y = -quat[1];
z = -quat[2];
}
if (!when.defined(result)) {
return new Quaternion(x, y, z, w);
}
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
const scratchHPRQuaternion$1 = new Quaternion();
let scratchHeadingQuaternion = new Quaternion();
let scratchPitchQuaternion = new Quaternion();
let scratchRollQuaternion = new Quaternion();
/**
* Computes a rotation from the given heading, pitch and roll angles. Heading is the rotation about the
* negative z axis. Pitch is the rotation about the negative y axis. Roll is the rotation about
* the positive x axis.
*
* @param {HeadingPitchRoll} headingPitchRoll The rotation expressed as a heading, pitch and roll.
* @param {Quaternion} [result] The object onto which to store the result.
* @returns {Quaternion} The modified result parameter or a new Quaternion instance if none was provided.
*/
Quaternion.fromHeadingPitchRoll = function (headingPitchRoll, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("headingPitchRoll", headingPitchRoll);
//>>includeEnd('debug');
scratchRollQuaternion = Quaternion.fromAxisAngle(
Matrix2.Cartesian3.UNIT_X,
headingPitchRoll.roll,
scratchHPRQuaternion$1
);
scratchPitchQuaternion = Quaternion.fromAxisAngle(
Matrix2.Cartesian3.UNIT_Y,
-headingPitchRoll.pitch,
result
);
result = Quaternion.multiply(
scratchPitchQuaternion,
scratchRollQuaternion,
scratchPitchQuaternion
);
scratchHeadingQuaternion = Quaternion.fromAxisAngle(
Matrix2.Cartesian3.UNIT_Z,
-headingPitchRoll.heading,
scratchHPRQuaternion$1
);
return Quaternion.multiply(scratchHeadingQuaternion, result, result);
};
const sampledQuaternionAxis = new Matrix2.Cartesian3();
const sampledQuaternionRotation = new Matrix2.Cartesian3();
const sampledQuaternionTempQuaternion = new Quaternion();
const sampledQuaternionQuaternion0 = new Quaternion();
const sampledQuaternionQuaternion0Conjugate = new Quaternion();
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
Quaternion.packedLength = 4;
/**
* Stores the provided instance into the provided array.
*
* @param {Quaternion} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*
* @returns {Number[]} The array that was packed into
*/
Quaternion.pack = function (value, array, startingIndex) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("value", value);
RuntimeError.Check.defined("array", array);
//>>includeEnd('debug');
startingIndex = when.defaultValue(startingIndex, 0);
array[startingIndex++] = value.x;
array[startingIndex++] = value.y;
array[startingIndex++] = value.z;
array[startingIndex] = value.w;
return array;
};
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Quaternion} [result] The object into which to store the result.
* @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
*/
Quaternion.unpack = function (array, startingIndex, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.defined("array", array);
//>>includeEnd('debug');
startingIndex = when.defaultValue(startingIndex, 0);
if (!when.defined(result)) {
result = new Quaternion();
}
result.x = array[startingIndex];
result.y = array[startingIndex + 1];
result.z = array[startingIndex + 2];
result.w = array[startingIndex + 3];
return result;
};
/**
* The number of elements used to store the object into an array in its interpolatable form.
* @type {Number}
*/
Quaternion.packedInterpolationLength = 3;
/**
* Converts a packed array into a form suitable for interpolation.
*
* @param {Number[]} packedArray The packed array.
* @param {Number} [startingIndex=0] The index of the first element to be converted.
* @param {Number} [lastIndex=packedArray.length] The index of the last element to be converted.
* @param {Number[]} [result] The object into which to store the result.
*/
Quaternion.convertPackedArrayForInterpolation = function (
packedArray,
startingIndex,
lastIndex,
result
) {
Quaternion.unpack(
packedArray,
lastIndex * 4,
sampledQuaternionQuaternion0Conjugate
);
Quaternion.conjugate(
sampledQuaternionQuaternion0Conjugate,
sampledQuaternionQuaternion0Conjugate
);
for (let i = 0, len = lastIndex - startingIndex + 1; i < len; i++) {
const offset = i * 3;
Quaternion.unpack(
packedArray,
(startingIndex + i) * 4,
sampledQuaternionTempQuaternion
);
Quaternion.multiply(
sampledQuaternionTempQuaternion,
sampledQuaternionQuaternion0Conjugate,
sampledQuaternionTempQuaternion
);
if (sampledQuaternionTempQuaternion.w < 0) {
Quaternion.negate(
sampledQuaternionTempQuaternion,
sampledQuaternionTempQuaternion
);
}
Quaternion.computeAxis(
sampledQuaternionTempQuaternion,
sampledQuaternionAxis
);
const angle = Quaternion.computeAngle(sampledQuaternionTempQuaternion);
if (!when.defined(result)) {
result = [];
}
result[offset] = sampledQuaternionAxis.x * angle;
result[offset + 1] = sampledQuaternionAxis.y * angle;
result[offset + 2] = sampledQuaternionAxis.z * angle;
}
};
/**
* Retrieves an instance from a packed array converted with {@link convertPackedArrayForInterpolation}.
*
* @param {Number[]} array The array previously packed for interpolation.
* @param {Number[]} sourceArray The original packed array.
* @param {Number} [firstIndex=0] The firstIndex used to convert the array.
* @param {Number} [lastIndex=packedArray.length] The lastIndex used to convert the array.
* @param {Quaternion} [result] The object into which to store the result.
* @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
*/
Quaternion.unpackInterpolationResult = function (
array,
sourceArray,
firstIndex,
lastIndex,
result
) {
if (!when.defined(result)) {
result = new Quaternion();
}
Matrix2.Cartesian3.fromArray(array, 0, sampledQuaternionRotation);
const magnitude = Matrix2.Cartesian3.magnitude(sampledQuaternionRotation);
Quaternion.unpack(sourceArray, lastIndex * 4, sampledQuaternionQuaternion0);
if (magnitude === 0) {
Quaternion.clone(Quaternion.IDENTITY, sampledQuaternionTempQuaternion);
} else {
Quaternion.fromAxisAngle(
sampledQuaternionRotation,
magnitude,
sampledQuaternionTempQuaternion
);
}
return Quaternion.multiply(
sampledQuaternionTempQuaternion,
sampledQuaternionQuaternion0,
result
);
};
/**
* Duplicates a Quaternion instance.
*
* @param {Quaternion} quaternion The quaternion to duplicate.
* @param {Quaternion} [result] The object onto which to store the result.
* @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided. (Returns undefined if quaternion is undefined)
*/
Quaternion.clone = function (quaternion, result) {
if (!when.defined(quaternion)) {
return undefined;
}
if (!when.defined(result)) {
return new Quaternion(
quaternion.x,
quaternion.y,
quaternion.z,
quaternion.w
);
}
result.x = quaternion.x;
result.y = quaternion.y;
result.z = quaternion.z;
result.w = quaternion.w;
return result;
};
/**
* Computes the conjugate of the provided quaternion.
*
* @param {Quaternion} quaternion The quaternion to conjugate.
* @param {Quaternion} result The object onto which to store the result.
* @returns {Quaternion} The modified result parameter.
*/
Quaternion.conjugate = function (quaternion, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("quaternion", quaternion);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
result.x = -quaternion.x;
result.y = -quaternion.y;
result.z = -quaternion.z;
result.w = quaternion.w;
return result;
};
/**
* Computes magnitude squared for the provided quaternion.
*
* @param {Quaternion} quaternion The quaternion to conjugate.
* @returns {Number} The magnitude squared.
*/
Quaternion.magnitudeSquared = function (quaternion) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("quaternion", quaternion);
//>>includeEnd('debug');
return (
quaternion.x * quaternion.x +
quaternion.y * quaternion.y +
quaternion.z * quaternion.z +
quaternion.w * quaternion.w
);
};
/**
* Computes magnitude for the provided quaternion.
*
* @param {Quaternion} quaternion The quaternion to conjugate.
* @returns {Number} The magnitude.
*/
Quaternion.magnitude = function (quaternion) {
return Math.sqrt(Quaternion.magnitudeSquared(quaternion));
};
/**
* Computes the normalized form of the provided quaternion.
*
* @param {Quaternion} quaternion The quaternion to normalize.
* @param {Quaternion} result The object onto which to store the result.
* @returns {Quaternion} The modified result parameter.
*/
Quaternion.normalize = function (quaternion, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
const inverseMagnitude = 1.0 / Quaternion.magnitude(quaternion);
const x = quaternion.x * inverseMagnitude;
const y = quaternion.y * inverseMagnitude;
const z = quaternion.z * inverseMagnitude;
const w = quaternion.w * inverseMagnitude;
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
/**
* Computes the inverse of the provided quaternion.
*
* @param {Quaternion} quaternion The quaternion to normalize.
* @param {Quaternion} result The object onto which to store the result.
* @returns {Quaternion} The modified result parameter.
*/
Quaternion.inverse = function (quaternion, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
const magnitudeSquared = Quaternion.magnitudeSquared(quaternion);
result = Quaternion.conjugate(quaternion, result);
return Quaternion.multiplyByScalar(result, 1.0 / magnitudeSquared, result);
};
/**
* Computes the componentwise sum of two quaternions.
*
* @param {Quaternion} left The first quaternion.
* @param {Quaternion} right The second quaternion.
* @param {Quaternion} result The object onto which to store the result.
* @returns {Quaternion} The modified result parameter.
*/
Quaternion.add = function (left, right, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("left", left);
RuntimeError.Check.typeOf.object("right", right);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
result.x = left.x + right.x;
result.y = left.y + right.y;
result.z = left.z + right.z;
result.w = left.w + right.w;
return result;
};
/**
* Computes the componentwise difference of two quaternions.
*
* @param {Quaternion} left The first quaternion.
* @param {Quaternion} right The second quaternion.
* @param {Quaternion} result The object onto which to store the result.
* @returns {Quaternion} The modified result parameter.
*/
Quaternion.subtract = function (left, right, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("left", left);
RuntimeError.Check.typeOf.object("right", right);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
result.x = left.x - right.x;
result.y = left.y - right.y;
result.z = left.z - right.z;
result.w = left.w - right.w;
return result;
};
/**
* Negates the provided quaternion.
*
* @param {Quaternion} quaternion The quaternion to be negated.
* @param {Quaternion} result The object onto which to store the result.
* @returns {Quaternion} The modified result parameter.
*/
Quaternion.negate = function (quaternion, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("quaternion", quaternion);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
result.x = -quaternion.x;
result.y = -quaternion.y;
result.z = -quaternion.z;
result.w = -quaternion.w;
return result;
};
/**
* Computes the dot (scalar) product of two quaternions.
*
* @param {Quaternion} left The first quaternion.
* @param {Quaternion} right The second quaternion.
* @returns {Number} The dot product.
*/
Quaternion.dot = function (left, right) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("left", left);
RuntimeError.Check.typeOf.object("right", right);
//>>includeEnd('debug');
return (
left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w
);
};
/**
* Computes the product of two quaternions.
*
* @param {Quaternion} left The first quaternion.
* @param {Quaternion} right The second quaternion.
* @param {Quaternion} result The object onto which to store the result.
* @returns {Quaternion} The modified result parameter.
*/
Quaternion.multiply = function (left, right, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("left", left);
RuntimeError.Check.typeOf.object("right", right);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
const leftX = left.x;
const leftY = left.y;
const leftZ = left.z;
const leftW = left.w;
const rightX = right.x;
const rightY = right.y;
const rightZ = right.z;
const rightW = right.w;
const x = leftW * rightX + leftX * rightW + leftY * rightZ - leftZ * rightY;
const y = leftW * rightY - leftX * rightZ + leftY * rightW + leftZ * rightX;
const z = leftW * rightZ + leftX * rightY - leftY * rightX + leftZ * rightW;
const w = leftW * rightW - leftX * rightX - leftY * rightY - leftZ * rightZ;
result.x = x;
result.y = y;
result.z = z;
result.w = w;
return result;
};
/**
* Multiplies the provided quaternion componentwise by the provided scalar.
*
* @param {Quaternion} quaternion The quaternion to be scaled.
* @param {Number} scalar The scalar to multiply with.
* @param {Quaternion} result The object onto which to store the result.
* @returns {Quaternion} The modified result parameter.
*/
Quaternion.multiplyByScalar = function (quaternion, scalar, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("quaternion", quaternion);
RuntimeError.Check.typeOf.number("scalar", scalar);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
result.x = quaternion.x * scalar;
result.y = quaternion.y * scalar;
result.z = quaternion.z * scalar;
result.w = quaternion.w * scalar;
return result;
};
/**
* Divides the provided quaternion componentwise by the provided scalar.
*
* @param {Quaternion} quaternion The quaternion to be divided.
* @param {Number} scalar The scalar to divide by.
* @param {Quaternion} result The object onto which to store the result.
* @returns {Quaternion} The modified result parameter.
*/
Quaternion.divideByScalar = function (quaternion, scalar, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("quaternion", quaternion);
RuntimeError.Check.typeOf.number("scalar", scalar);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
result.x = quaternion.x / scalar;
result.y = quaternion.y / scalar;
result.z = quaternion.z / scalar;
result.w = quaternion.w / scalar;
return result;
};
/**
* Computes the axis of rotation of the provided quaternion.
*
* @param {Quaternion} quaternion The quaternion to use.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Quaternion.computeAxis = function (quaternion, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("quaternion", quaternion);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
const w = quaternion.w;
if (Math.abs(w - 1.0) < ComponentDatatype.CesiumMath.EPSILON6) {
result.x = result.y = result.z = 0;
return result;
}
const scalar = 1.0 / Math.sqrt(1.0 - w * w);
result.x = quaternion.x * scalar;
result.y = quaternion.y * scalar;
result.z = quaternion.z * scalar;
return result;
};
/**
* Computes the angle of rotation of the provided quaternion.
*
* @param {Quaternion} quaternion The quaternion to use.
* @returns {Number} The angle of rotation.
*/
Quaternion.computeAngle = function (quaternion) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("quaternion", quaternion);
//>>includeEnd('debug');
if (Math.abs(quaternion.w - 1.0) < ComponentDatatype.CesiumMath.EPSILON6) {
return 0.0;
}
return 2.0 * Math.acos(quaternion.w);
};
let lerpScratch = new Quaternion();
/**
* Computes the linear interpolation or extrapolation at t using the provided quaternions.
*
* @param {Quaternion} start The value corresponding to t at 0.0.
* @param {Quaternion} end The value corresponding to t at 1.0.
* @param {Number} t The point along t at which to interpolate.
* @param {Quaternion} result The object onto which to store the result.
* @returns {Quaternion} The modified result parameter.
*/
Quaternion.lerp = function (start, end, t, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("start", start);
RuntimeError.Check.typeOf.object("end", end);
RuntimeError.Check.typeOf.number("t", t);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
lerpScratch = Quaternion.multiplyByScalar(end, t, lerpScratch);
result = Quaternion.multiplyByScalar(start, 1.0 - t, result);
return Quaternion.add(lerpScratch, result, result);
};
let slerpEndNegated = new Quaternion();
let slerpScaledP = new Quaternion();
let slerpScaledR = new Quaternion();
/**
* Computes the spherical linear interpolation or extrapolation at t using the provided quaternions.
*
* @param {Quaternion} start The value corresponding to t at 0.0.
* @param {Quaternion} end The value corresponding to t at 1.0.
* @param {Number} t The point along t at which to interpolate.
* @param {Quaternion} result The object onto which to store the result.
* @returns {Quaternion} The modified result parameter.
*
* @see Quaternion#fastSlerp
*/
Quaternion.slerp = function (start, end, t, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("start", start);
RuntimeError.Check.typeOf.object("end", end);
RuntimeError.Check.typeOf.number("t", t);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
let dot = Quaternion.dot(start, end);
// The angle between start must be acute. Since q and -q represent
// the same rotation, negate q to get the acute angle.
let r = end;
if (dot < 0.0) {
dot = -dot;
r = slerpEndNegated = Quaternion.negate(end, slerpEndNegated);
}
// dot > 0, as the dot product approaches 1, the angle between the
// quaternions vanishes. use linear interpolation.
if (1.0 - dot < ComponentDatatype.CesiumMath.EPSILON6) {
return Quaternion.lerp(start, r, t, result);
}
const theta = Math.acos(dot);
slerpScaledP = Quaternion.multiplyByScalar(
start,
Math.sin((1 - t) * theta),
slerpScaledP
);
slerpScaledR = Quaternion.multiplyByScalar(
r,
Math.sin(t * theta),
slerpScaledR
);
result = Quaternion.add(slerpScaledP, slerpScaledR, result);
return Quaternion.multiplyByScalar(result, 1.0 / Math.sin(theta), result);
};
/**
* The logarithmic quaternion function.
*
* @param {Quaternion} quaternion The unit quaternion.
* @param {Cartesian3} result The object onto which to store the result.
* @returns {Cartesian3} The modified result parameter.
*/
Quaternion.log = function (quaternion, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("quaternion", quaternion);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
const theta = ComponentDatatype.CesiumMath.acosClamped(quaternion.w);
let thetaOverSinTheta = 0.0;
if (theta !== 0.0) {
thetaOverSinTheta = theta / Math.sin(theta);
}
return Matrix2.Cartesian3.multiplyByScalar(quaternion, thetaOverSinTheta, result);
};
/**
* The exponential quaternion function.
*
* @param {Cartesian3} cartesian The cartesian.
* @param {Quaternion} result The object onto which to store the result.
* @returns {Quaternion} The modified result parameter.
*/
Quaternion.exp = function (cartesian, result) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("cartesian", cartesian);
RuntimeError.Check.typeOf.object("result", result);
//>>includeEnd('debug');
const theta = Matrix2.Cartesian3.magnitude(cartesian);
let sinThetaOverTheta = 0.0;
if (theta !== 0.0) {
sinThetaOverTheta = Math.sin(theta) / theta;
}
result.x = cartesian.x * sinThetaOverTheta;
result.y = cartesian.y * sinThetaOverTheta;
result.z = cartesian.z * sinThetaOverTheta;
result.w = Math.cos(theta);
return result;
};
const squadScratchCartesian0 = new Matrix2.Cartesian3();
const squadScratchCartesian1 = new Matrix2.Cartesian3();
const squadScratchQuaternion0 = new Quaternion();
const squadScratchQuaternion1 = new Quaternion();
/**
* Computes an inner quadrangle point.
*
This will compute quaternions that ensure a squad curve is C1.
* * @param {Quaternion} q0 The first quaternion. * @param {Quaternion} q1 The second quaternion. * @param {Quaternion} q2 The third quaternion. * @param {Quaternion} result The object onto which to store the result. * @returns {Quaternion} The modified result parameter. * * @see Quaternion#squad */ Quaternion.computeInnerQuadrangle = function (q0, q1, q2, result) { //>>includeStart('debug', pragmas.debug); RuntimeError.Check.typeOf.object("q0", q0); RuntimeError.Check.typeOf.object("q1", q1); RuntimeError.Check.typeOf.object("q2", q2); RuntimeError.Check.typeOf.object("result", result); //>>includeEnd('debug'); const qInv = Quaternion.conjugate(q1, squadScratchQuaternion0); Quaternion.multiply(qInv, q2, squadScratchQuaternion1); const cart0 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian0); Quaternion.multiply(qInv, q0, squadScratchQuaternion1); const cart1 = Quaternion.log(squadScratchQuaternion1, squadScratchCartesian1); Matrix2.Cartesian3.add(cart0, cart1, cart0); Matrix2.Cartesian3.multiplyByScalar(cart0, 0.25, cart0); Matrix2.Cartesian3.negate(cart0, cart0); Quaternion.exp(cart0, squadScratchQuaternion0); return Quaternion.multiply(q1, squadScratchQuaternion0, result); }; /** * Computes the spherical quadrangle interpolation between quaternions. * * @param {Quaternion} q0 The first quaternion. * @param {Quaternion} q1 The second quaternion. * @param {Quaternion} s0 The first inner quadrangle. * @param {Quaternion} s1 The second inner quadrangle. * @param {Number} t The time in [0,1] used to interpolate. * @param {Quaternion} result The object onto which to store the result. * @returns {Quaternion} The modified result parameter. * * * @example * // 1. compute the squad interpolation between two quaternions on a curve * const s0 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i - 1], quaternions[i], quaternions[i + 1], new Cesium.Quaternion()); * const s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[i], quaternions[i + 1], quaternions[i + 2], new Cesium.Quaternion()); * const q = Cesium.Quaternion.squad(quaternions[i], quaternions[i + 1], s0, s1, t, new Cesium.Quaternion()); * * // 2. compute the squad interpolation as above but where the first quaternion is a end point. * const s1 = Cesium.Quaternion.computeInnerQuadrangle(quaternions[0], quaternions[1], quaternions[2], new Cesium.Quaternion()); * const q = Cesium.Quaternion.squad(quaternions[0], quaternions[1], quaternions[0], s1, t, new Cesium.Quaternion()); * * @see Quaternion#computeInnerQuadrangle */ Quaternion.squad = function (q0, q1, s0, s1, t, result) { //>>includeStart('debug', pragmas.debug); RuntimeError.Check.typeOf.object("q0", q0); RuntimeError.Check.typeOf.object("q1", q1); RuntimeError.Check.typeOf.object("s0", s0); RuntimeError.Check.typeOf.object("s1", s1); RuntimeError.Check.typeOf.number("t", t); RuntimeError.Check.typeOf.object("result", result); //>>includeEnd('debug'); const slerp0 = Quaternion.slerp(q0, q1, t, squadScratchQuaternion0); const slerp1 = Quaternion.slerp(s0, s1, t, squadScratchQuaternion1); return Quaternion.slerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result); }; const fastSlerpScratchQuaternion = new Quaternion(); const opmu = 1.90110745351730037; const u = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : []; const v = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : []; const bT = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : []; const bD = FeatureDetection.supportsTypedArrays() ? new Float32Array(8) : []; for (let i = 0; i < 7; ++i) { const s = i + 1.0; const t = 2.0 * s + 1.0; u[i] = 1.0 / (s * t); v[i] = s / t; } u[7] = opmu / (8.0 * 17.0); v[7] = (opmu * 8.0) / 17.0; /** * Computes the spherical linear interpolation or extrapolation at t using the provided quaternions. * This implementation is faster than {@link Quaternion#slerp}, but is only accurate up to 10-6. * * @param {Quaternion} start The value corresponding to t at 0.0. * @param {Quaternion} end The value corresponding to t at 1.0. * @param {Number} t The point along t at which to interpolate. * @param {Quaternion} result The object onto which to store the result. * @returns {Quaternion} The modified result parameter. * * @see Quaternion#slerp */ Quaternion.fastSlerp = function (start, end, t, result) { //>>includeStart('debug', pragmas.debug); RuntimeError.Check.typeOf.object("start", start); RuntimeError.Check.typeOf.object("end", end); RuntimeError.Check.typeOf.number("t", t); RuntimeError.Check.typeOf.object("result", result); //>>includeEnd('debug'); let x = Quaternion.dot(start, end); let sign; if (x >= 0) { sign = 1.0; } else { sign = -1.0; x = -x; } const xm1 = x - 1.0; const d = 1.0 - t; const sqrT = t * t; const sqrD = d * d; for (let i = 7; i >= 0; --i) { bT[i] = (u[i] * sqrT - v[i]) * xm1; bD[i] = (u[i] * sqrD - v[i]) * xm1; } const cT = sign * t * (1.0 + bT[0] * (1.0 + bT[1] * (1.0 + bT[2] * (1.0 + bT[3] * (1.0 + bT[4] * (1.0 + bT[5] * (1.0 + bT[6] * (1.0 + bT[7])))))))); const cD = d * (1.0 + bD[0] * (1.0 + bD[1] * (1.0 + bD[2] * (1.0 + bD[3] * (1.0 + bD[4] * (1.0 + bD[5] * (1.0 + bD[6] * (1.0 + bD[7])))))))); const temp = Quaternion.multiplyByScalar( start, cD, fastSlerpScratchQuaternion ); Quaternion.multiplyByScalar(end, cT, result); return Quaternion.add(temp, result, result); }; /** * Computes the spherical quadrangle interpolation between quaternions. * An implementation that is faster than {@link Quaternion#squad}, but less accurate. * * @param {Quaternion} q0 The first quaternion. * @param {Quaternion} q1 The second quaternion. * @param {Quaternion} s0 The first inner quadrangle. * @param {Quaternion} s1 The second inner quadrangle. * @param {Number} t The time in [0,1] used to interpolate. * @param {Quaternion} result The object onto which to store the result. * @returns {Quaternion} The modified result parameter or a new instance if none was provided. * * @see Quaternion#squad */ Quaternion.fastSquad = function (q0, q1, s0, s1, t, result) { //>>includeStart('debug', pragmas.debug); RuntimeError.Check.typeOf.object("q0", q0); RuntimeError.Check.typeOf.object("q1", q1); RuntimeError.Check.typeOf.object("s0", s0); RuntimeError.Check.typeOf.object("s1", s1); RuntimeError.Check.typeOf.number("t", t); RuntimeError.Check.typeOf.object("result", result); //>>includeEnd('debug'); const slerp0 = Quaternion.fastSlerp(q0, q1, t, squadScratchQuaternion0); const slerp1 = Quaternion.fastSlerp(s0, s1, t, squadScratchQuaternion1); return Quaternion.fastSlerp(slerp0, slerp1, 2.0 * t * (1.0 - t), result); }; /** * Compares the provided quaternions componentwise and returns *true
if they are equal, false
otherwise.
*
* @param {Quaternion} [left] The first quaternion.
* @param {Quaternion} [right] The second quaternion.
* @returns {Boolean} true
if left and right are equal, false
otherwise.
*/
Quaternion.equals = function (left, right) {
return (
left === right ||
(when.defined(left) &&
when.defined(right) &&
left.x === right.x &&
left.y === right.y &&
left.z === right.z &&
left.w === right.w)
);
};
/**
* Compares the provided quaternions componentwise and returns
* true
if they are within the provided epsilon,
* false
otherwise.
*
* @param {Quaternion} [left] The first quaternion.
* @param {Quaternion} [right] The second quaternion.
* @param {Number} [epsilon=0] The epsilon to use for equality testing.
* @returns {Boolean} true
if left and right are within the provided epsilon, false
otherwise.
*/
Quaternion.equalsEpsilon = function (left, right, epsilon) {
epsilon = when.defaultValue(epsilon, 0);
return (
left === right ||
(when.defined(left) &&
when.defined(right) &&
Math.abs(left.x - right.x) <= epsilon &&
Math.abs(left.y - right.y) <= epsilon &&
Math.abs(left.z - right.z) <= epsilon &&
Math.abs(left.w - right.w) <= epsilon)
);
};
/**
* An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 0.0).
*
* @type {Quaternion}
* @constant
*/
Quaternion.ZERO = Object.freeze(new Quaternion(0.0, 0.0, 0.0, 0.0));
/**
* An immutable Quaternion instance initialized to (0.0, 0.0, 0.0, 1.0).
*
* @type {Quaternion}
* @constant
*/
Quaternion.IDENTITY = Object.freeze(new Quaternion(0.0, 0.0, 0.0, 1.0));
/**
* Duplicates this Quaternion instance.
*
* @param {Quaternion} [result] The object onto which to store the result.
* @returns {Quaternion} The modified result parameter or a new Quaternion instance if one was not provided.
*/
Quaternion.prototype.clone = function (result) {
return Quaternion.clone(this, result);
};
/**
* Compares this and the provided quaternion componentwise and returns
* true
if they are equal, false
otherwise.
*
* @param {Quaternion} [right] The right hand side quaternion.
* @returns {Boolean} true
if left and right are equal, false
otherwise.
*/
Quaternion.prototype.equals = function (right) {
return Quaternion.equals(this, right);
};
/**
* Compares this and the provided quaternion componentwise and returns
* true
if they are within the provided epsilon,
* false
otherwise.
*
* @param {Quaternion} [right] The right hand side quaternion.
* @param {Number} [epsilon=0] The epsilon to use for equality testing.
* @returns {Boolean} true
if left and right are within the provided epsilon, false
otherwise.
*/
Quaternion.prototype.equalsEpsilon = function (right, epsilon) {
return Quaternion.equalsEpsilon(this, right, epsilon);
};
/**
* Returns a string representing this quaternion in the format (x, y, z, w).
*
* @returns {String} A string representing this Quaternion.
*/
Quaternion.prototype.toString = function () {
return `(${this.x}, ${this.y}, ${this.z}, ${this.w})`;
};
/**
* Finds an item in a sorted array.
*
* @function
* @param {Array} array The sorted array to search.
* @param {*} itemToFind The item to find in the array.
* @param {binarySearchComparator} comparator The function to use to compare the item to
* elements in the array.
* @returns {Number} The index of itemToFind
in the array, if it exists. If itemToFind
* does not exist, the return value is a negative number which is the bitwise complement (~)
* of the index before which the itemToFind should be inserted in order to maintain the
* sorted order of the array.
*
* @example
* // Create a comparator function to search through an array of numbers.
* function comparator(a, b) {
* return a - b;
* };
* const numbers = [0, 2, 4, 6, 8];
* const index = Cesium.binarySearch(numbers, 6, comparator); // 3
*/
function binarySearch(array, itemToFind, comparator) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.defined("array", array);
RuntimeError.Check.defined("itemToFind", itemToFind);
RuntimeError.Check.defined("comparator", comparator);
//>>includeEnd('debug');
let low = 0;
let high = array.length - 1;
let i;
let comparison;
while (low <= high) {
i = ~~((low + high) / 2);
comparison = comparator(array[i], itemToFind);
if (comparison < 0) {
low = i + 1;
continue;
}
if (comparison > 0) {
high = i - 1;
continue;
}
return i;
}
return ~(high + 1);
}
/**
* A set of Earth Orientation Parameters (EOP) sampled at a time.
*
* @alias EarthOrientationParametersSample
* @constructor
*
* @param {Number} xPoleWander The pole wander about the X axis, in radians.
* @param {Number} yPoleWander The pole wander about the Y axis, in radians.
* @param {Number} xPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
* @param {Number} yPoleOffset The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
* @param {Number} ut1MinusUtc The difference in time standards, UT1 - UTC, in seconds.
*
* @private
*/
function EarthOrientationParametersSample(
xPoleWander,
yPoleWander,
xPoleOffset,
yPoleOffset,
ut1MinusUtc
) {
/**
* The pole wander about the X axis, in radians.
* @type {Number}
*/
this.xPoleWander = xPoleWander;
/**
* The pole wander about the Y axis, in radians.
* @type {Number}
*/
this.yPoleWander = yPoleWander;
/**
* The offset to the Celestial Intermediate Pole (CIP) about the X axis, in radians.
* @type {Number}
*/
this.xPoleOffset = xPoleOffset;
/**
* The offset to the Celestial Intermediate Pole (CIP) about the Y axis, in radians.
* @type {Number}
*/
this.yPoleOffset = yPoleOffset;
/**
* The difference in time standards, UT1 - UTC, in seconds.
* @type {Number}
*/
this.ut1MinusUtc = ut1MinusUtc;
}
/**
* Represents a Gregorian date in a more precise format than the JavaScript Date object.
* In addition to submillisecond precision, this object can also represent leap seconds.
* @alias GregorianDate
* @constructor
*
* @param {Number} [year] The year as a whole number.
* @param {Number} [month] The month as a whole number with range [1, 12].
* @param {Number} [day] The day of the month as a whole number starting at 1.
* @param {Number} [hour] The hour as a whole number with range [0, 23].
* @param {Number} [minute] The minute of the hour as a whole number with range [0, 59].
* @param {Number} [second] The second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
* @param {Number} [millisecond] The millisecond of the second as a floating point number with range [0.0, 1000.0).
* @param {Boolean} [isLeapSecond] Whether this time is during a leap second.
*
* @see JulianDate#toGregorianDate
*/
function GregorianDate(
year,
month,
day,
hour,
minute,
second,
millisecond,
isLeapSecond
) {
/**
* Gets or sets the year as a whole number.
* @type {Number}
*/
this.year = year;
/**
* Gets or sets the month as a whole number with range [1, 12].
* @type {Number}
*/
this.month = month;
/**
* Gets or sets the day of the month as a whole number starting at 1.
* @type {Number}
*/
this.day = day;
/**
* Gets or sets the hour as a whole number with range [0, 23].
* @type {Number}
*/
this.hour = hour;
/**
* Gets or sets the minute of the hour as a whole number with range [0, 59].
* @type {Number}
*/
this.minute = minute;
/**
* Gets or sets the second of the minute as a whole number with range [0, 60], with 60 representing a leap second.
* @type {Number}
*/
this.second = second;
/**
* Gets or sets the millisecond of the second as a floating point number with range [0.0, 1000.0).
* @type {Number}
*/
this.millisecond = millisecond;
/**
* Gets or sets whether this time is during a leap second.
* @type {Boolean}
*/
this.isLeapSecond = isLeapSecond;
}
/**
* Determines if a given date is a leap year.
*
* @function isLeapYear
*
* @param {Number} year The year to be tested.
* @returns {Boolean} True if year
is a leap year.
*
* @example
* const leapYear = Cesium.isLeapYear(2000); // true
*/
function isLeapYear(year) {
//>>includeStart('debug', pragmas.debug);
if (year === null || isNaN(year)) {
throw new RuntimeError.DeveloperError("year is required and must be a number.");
}
//>>includeEnd('debug');
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
/**
* Describes a single leap second, which is constructed from a {@link JulianDate} and a
* numerical offset representing the number of seconds TAI is ahead of the UTC time standard.
* @alias LeapSecond
* @constructor
*
* @param {JulianDate} [date] A Julian date representing the time of the leap second.
* @param {Number} [offset] The cumulative number of seconds that TAI is ahead of UTC at the provided date.
*/
function LeapSecond(date, offset) {
/**
* Gets or sets the date at which this leap second occurs.
* @type {JulianDate}
*/
this.julianDate = date;
/**
* Gets or sets the cumulative number of seconds between the UTC and TAI time standards at the time
* of this leap second.
* @type {Number}
*/
this.offset = offset;
}
/**
* Constants for time conversions like those done by {@link JulianDate}.
*
* @namespace TimeConstants
*
* @see JulianDate
*
* @private
*/
const TimeConstants = {
/**
* The number of seconds in one millisecond: 0.001
* @type {Number}
* @constant
*/
SECONDS_PER_MILLISECOND: 0.001,
/**
* The number of seconds in one minute: 60
.
* @type {Number}
* @constant
*/
SECONDS_PER_MINUTE: 60.0,
/**
* The number of minutes in one hour: 60
.
* @type {Number}
* @constant
*/
MINUTES_PER_HOUR: 60.0,
/**
* The number of hours in one day: 24
.
* @type {Number}
* @constant
*/
HOURS_PER_DAY: 24.0,
/**
* The number of seconds in one hour: 3600
.
* @type {Number}
* @constant
*/
SECONDS_PER_HOUR: 3600.0,
/**
* The number of minutes in one day: 1440
.
* @type {Number}
* @constant
*/
MINUTES_PER_DAY: 1440.0,
/**
* The number of seconds in one day, ignoring leap seconds: 86400
.
* @type {Number}
* @constant
*/
SECONDS_PER_DAY: 86400.0,
/**
* The number of days in one Julian century: 36525
.
* @type {Number}
* @constant
*/
DAYS_PER_JULIAN_CENTURY: 36525.0,
/**
* One trillionth of a second.
* @type {Number}
* @constant
*/
PICOSECOND: 0.000000001,
/**
* The number of days to subtract from a Julian date to determine the
* modified Julian date, which gives the number of days since midnight
* on November 17, 1858.
* @type {Number}
* @constant
*/
MODIFIED_JULIAN_DATE_DIFFERENCE: 2400000.5,
};
var TimeConstants$1 = Object.freeze(TimeConstants);
/**
* Provides the type of time standards which JulianDate can take as input.
*
* @enum {Number}
*
* @see JulianDate
*/
const TimeStandard = {
/**
* Represents the coordinated Universal Time (UTC) time standard.
*
* UTC is related to TAI according to the relationship
* UTC = TAI - deltaT
where deltaT
is the number of leap
* seconds which have been introduced as of the time in TAI.
*
* @type {Number}
* @constant
*/
UTC: 0,
/**
* Represents the International Atomic Time (TAI) time standard.
* TAI is the principal time standard to which the other time standards are related.
*
* @type {Number}
* @constant
*/
TAI: 1,
};
var TimeStandard$1 = Object.freeze(TimeStandard);
const gregorianDateScratch = new GregorianDate();
const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const daysInLeapFeburary = 29;
function compareLeapSecondDates$1(leapSecond, dateToFind) {
return JulianDate.compare(leapSecond.julianDate, dateToFind.julianDate);
}
// we don't really need a leap second instance, anything with a julianDate property will do
const binarySearchScratchLeapSecond = new LeapSecond();
function convertUtcToTai(julianDate) {
//Even though julianDate is in UTC, we'll treat it as TAI and
//search the leap second table for it.
binarySearchScratchLeapSecond.julianDate = julianDate;
const leapSeconds = JulianDate.leapSeconds;
let index = binarySearch(
leapSeconds,
binarySearchScratchLeapSecond,
compareLeapSecondDates$1
);
if (index < 0) {
index = ~index;
}
if (index >= leapSeconds.length) {
index = leapSeconds.length - 1;
}
let offset = leapSeconds[index].offset;
if (index > 0) {
//Now we have the index of the closest leap second that comes on or after our UTC time.
//However, if the difference between the UTC date being converted and the TAI
//defined leap second is greater than the offset, we are off by one and need to use
//the previous leap second.
const difference = JulianDate.secondsDifference(
leapSeconds[index].julianDate,
julianDate
);
if (difference > offset) {
index--;
offset = leapSeconds[index].offset;
}
}
JulianDate.addSeconds(julianDate, offset, julianDate);
}
function convertTaiToUtc(julianDate, result) {
binarySearchScratchLeapSecond.julianDate = julianDate;
const leapSeconds = JulianDate.leapSeconds;
let index = binarySearch(
leapSeconds,
binarySearchScratchLeapSecond,
compareLeapSecondDates$1
);
if (index < 0) {
index = ~index;
}
//All times before our first leap second get the first offset.
if (index === 0) {
return JulianDate.addSeconds(julianDate, -leapSeconds[0].offset, result);
}
//All times after our leap second get the last offset.
if (index >= leapSeconds.length) {
return JulianDate.addSeconds(
julianDate,
-leapSeconds[index - 1].offset,
result
);
}
//Compute the difference between the found leap second and the time we are converting.
const difference = JulianDate.secondsDifference(
leapSeconds[index].julianDate,
julianDate
);
if (difference === 0) {
//The date is in our leap second table.
return JulianDate.addSeconds(
julianDate,
-leapSeconds[index].offset,
result
);
}
if (difference <= 1.0) {
//The requested date is during the moment of a leap second, then we cannot convert to UTC
return undefined;
}
//The time is in between two leap seconds, index is the leap second after the date
//we're converting, so we subtract one to get the correct LeapSecond instance.
return JulianDate.addSeconds(
julianDate,
-leapSeconds[--index].offset,
result
);
}
function setComponents(wholeDays, secondsOfDay, julianDate) {
const extraDays = (secondsOfDay / TimeConstants$1.SECONDS_PER_DAY) | 0;
wholeDays += extraDays;
secondsOfDay -= TimeConstants$1.SECONDS_PER_DAY * extraDays;
if (secondsOfDay < 0) {
wholeDays--;
secondsOfDay += TimeConstants$1.SECONDS_PER_DAY;
}
julianDate.dayNumber = wholeDays;
julianDate.secondsOfDay = secondsOfDay;
return julianDate;
}
function computeJulianDateComponents(
year,
month,
day,
hour,
minute,
second,
millisecond
) {
// Algorithm from page 604 of the Explanatory Supplement to the
// Astronomical Almanac (Seidelmann 1992).
const a = ((month - 14) / 12) | 0;
const b = year + 4800 + a;
let dayNumber =
(((1461 * b) / 4) | 0) +
(((367 * (month - 2 - 12 * a)) / 12) | 0) -
(((3 * (((b + 100) / 100) | 0)) / 4) | 0) +
day -
32075;
// JulianDates are noon-based
hour = hour - 12;
if (hour < 0) {
hour += 24;
}
const secondsOfDay =
second +
(hour * TimeConstants$1.SECONDS_PER_HOUR +
minute * TimeConstants$1.SECONDS_PER_MINUTE +
millisecond * TimeConstants$1.SECONDS_PER_MILLISECOND);
if (secondsOfDay >= 43200.0) {
dayNumber -= 1;
}
return [dayNumber, secondsOfDay];
}
//Regular expressions used for ISO8601 date parsing.
//YYYY
const matchCalendarYear = /^(\d{4})$/;
//YYYY-MM (YYYYMM is invalid)
const matchCalendarMonth = /^(\d{4})-(\d{2})$/;
//YYYY-DDD or YYYYDDD
const matchOrdinalDate = /^(\d{4})-?(\d{3})$/;
//YYYY-Www or YYYYWww or YYYY-Www-D or YYYYWwwD
const matchWeekDate = /^(\d{4})-?W(\d{2})-?(\d{1})?$/;
//YYYY-MM-DD or YYYYMMDD
const matchCalendarDate = /^(\d{4})-?(\d{2})-?(\d{2})$/;
// Match utc offset
const utcOffset = /([Z+\-])?(\d{2})?:?(\d{2})?$/;
// Match hours HH or HH.xxxxx
const matchHours = /^(\d{2})(\.\d+)?/.source + utcOffset.source;
// Match hours/minutes HH:MM HHMM.xxxxx
const matchHoursMinutes = /^(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
// Match hours/minutes HH:MM:SS HHMMSS.xxxxx
const matchHoursMinutesSeconds =
/^(\d{2}):?(\d{2}):?(\d{2})(\.\d+)?/.source + utcOffset.source;
const iso8601ErrorMessage = "Invalid ISO 8601 date.";
/**
* Represents an astronomical Julian date, which is the number of days since noon on January 1, -4712 (4713 BC).
* For increased precision, this class stores the whole number part of the date and the seconds
* part of the date in separate components. In order to be safe for arithmetic and represent
* leap seconds, the date is always stored in the International Atomic Time standard
* {@link TimeStandard.TAI}.
* @alias JulianDate
* @constructor
*
* @param {Number} [julianDayNumber=0.0] The Julian Day Number representing the number of whole days. Fractional days will also be handled correctly.
* @param {Number} [secondsOfDay=0.0] The number of seconds into the current Julian Day Number. Fractional seconds, negative seconds and seconds greater than a day will be handled correctly.
* @param {TimeStandard} [timeStandard=TimeStandard.UTC] The time standard in which the first two parameters are defined.
*/
function JulianDate(julianDayNumber, secondsOfDay, timeStandard) {
/**
* Gets or sets the number of whole days.
* @type {Number}
*/
this.dayNumber = undefined;
/**
* Gets or sets the number of seconds into the current day.
* @type {Number}
*/
this.secondsOfDay = undefined;
julianDayNumber = when.defaultValue(julianDayNumber, 0.0);
secondsOfDay = when.defaultValue(secondsOfDay, 0.0);
timeStandard = when.defaultValue(timeStandard, TimeStandard$1.UTC);
//If julianDayNumber is fractional, make it an integer and add the number of seconds the fraction represented.
const wholeDays = julianDayNumber | 0;
secondsOfDay =
secondsOfDay +
(julianDayNumber - wholeDays) * TimeConstants$1.SECONDS_PER_DAY;
setComponents(wholeDays, secondsOfDay, this);
if (timeStandard === TimeStandard$1.UTC) {
convertUtcToTai(this);
}
}
/**
* Creates a new instance from a GregorianDate.
*
* @param {GregorianDate} date A GregorianDate.
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*
* @exception {DeveloperError} date must be a valid GregorianDate.
*/
JulianDate.fromGregorianDate = function (date, result) {
//>>includeStart('debug', pragmas.debug);
if (!(date instanceof GregorianDate)) {
throw new RuntimeError.DeveloperError("date must be a valid GregorianDate.");
}
//>>includeEnd('debug');
const components = computeJulianDateComponents(
date.year,
date.month,
date.day,
date.hour,
date.minute,
date.second,
date.millisecond
);
if (!when.defined(result)) {
return new JulianDate(components[0], components[1], TimeStandard$1.UTC);
}
setComponents(components[0], components[1], result);
convertUtcToTai(result);
return result;
};
/**
* Creates a new instance from a JavaScript Date.
*
* @param {Date} date A JavaScript Date.
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*
* @exception {DeveloperError} date must be a valid JavaScript Date.
*/
JulianDate.fromDate = function (date, result) {
//>>includeStart('debug', pragmas.debug);
if (!(date instanceof Date) || isNaN(date.getTime())) {
throw new RuntimeError.DeveloperError("date must be a valid JavaScript Date.");
}
//>>includeEnd('debug');
const components = computeJulianDateComponents(
date.getUTCFullYear(),
date.getUTCMonth() + 1,
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds(),
date.getUTCMilliseconds()
);
if (!when.defined(result)) {
return new JulianDate(components[0], components[1], TimeStandard$1.UTC);
}
setComponents(components[0], components[1], result);
convertUtcToTai(result);
return result;
};
/**
* Creates a new instance from a from an {@link http://en.wikipedia.org/wiki/ISO_8601|ISO 8601} date.
* This method is superior to Date.parse
because it will handle all valid formats defined by the ISO 8601
* specification, including leap seconds and sub-millisecond times, which discarded by most JavaScript implementations.
*
* @param {String} iso8601String An ISO 8601 date.
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*
* @exception {DeveloperError} Invalid ISO 8601 date.
*/
JulianDate.fromIso8601 = function (iso8601String, result) {
//>>includeStart('debug', pragmas.debug);
if (typeof iso8601String !== "string") {
throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug');
//Comma and decimal point both indicate a fractional number according to ISO 8601,
//start out by blanket replacing , with . which is the only valid such symbol in JS.
iso8601String = iso8601String.replace(",", ".");
//Split the string into its date and time components, denoted by a mandatory T
let tokens = iso8601String.split("T");
let year;
let month = 1;
let day = 1;
let hour = 0;
let minute = 0;
let second = 0;
let millisecond = 0;
//Lacking a time is okay, but a missing date is illegal.
const date = tokens[0];
const time = tokens[1];
let tmp;
let inLeapYear;
//>>includeStart('debug', pragmas.debug);
if (!when.defined(date)) {
throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
}
let dashCount;
//>>includeEnd('debug');
//First match the date against possible regular expressions.
tokens = date.match(matchCalendarDate);
if (tokens !== null) {
//>>includeStart('debug', pragmas.debug);
dashCount = date.split("-").length - 1;
if (dashCount > 0 && dashCount !== 2) {
throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug');
year = +tokens[1];
month = +tokens[2];
day = +tokens[3];
} else {
tokens = date.match(matchCalendarMonth);
if (tokens !== null) {
year = +tokens[1];
month = +tokens[2];
} else {
tokens = date.match(matchCalendarYear);
if (tokens !== null) {
year = +tokens[1];
} else {
//Not a year/month/day so it must be an ordinal date.
let dayOfYear;
tokens = date.match(matchOrdinalDate);
if (tokens !== null) {
year = +tokens[1];
dayOfYear = +tokens[2];
inLeapYear = isLeapYear(year);
//This validation is only applicable for this format.
//>>includeStart('debug', pragmas.debug);
if (
dayOfYear < 1 ||
(inLeapYear && dayOfYear > 366) ||
(!inLeapYear && dayOfYear > 365)
) {
throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug')
} else {
tokens = date.match(matchWeekDate);
if (tokens !== null) {
//ISO week date to ordinal date from
//http://en.wikipedia.org/w/index.php?title=ISO_week_date&oldid=474176775
year = +tokens[1];
const weekNumber = +tokens[2];
const dayOfWeek = +tokens[3] || 0;
//>>includeStart('debug', pragmas.debug);
dashCount = date.split("-").length - 1;
if (
dashCount > 0 &&
((!when.defined(tokens[3]) && dashCount !== 1) ||
(when.defined(tokens[3]) && dashCount !== 2))
) {
throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug')
const january4 = new Date(Date.UTC(year, 0, 4));
dayOfYear = weekNumber * 7 + dayOfWeek - january4.getUTCDay() - 3;
} else {
//None of our regular expressions succeeded in parsing the date properly.
//>>includeStart('debug', pragmas.debug);
throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
//>>includeEnd('debug')
}
}
//Split an ordinal date into month/day.
tmp = new Date(Date.UTC(year, 0, 1));
tmp.setUTCDate(dayOfYear);
month = tmp.getUTCMonth() + 1;
day = tmp.getUTCDate();
}
}
}
//Now that we have all of the date components, validate them to make sure nothing is out of range.
inLeapYear = isLeapYear(year);
//>>includeStart('debug', pragmas.debug);
if (
month < 1 ||
month > 12 ||
day < 1 ||
((month !== 2 || !inLeapYear) && day > daysInMonth[month - 1]) ||
(inLeapYear && month === 2 && day > daysInLeapFeburary)
) {
throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug')
//Now move onto the time string, which is much simpler.
//If no time is specified, it is considered the beginning of the day, UTC to match Javascript's implementation.
let offsetIndex;
if (when.defined(time)) {
tokens = time.match(matchHoursMinutesSeconds);
if (tokens !== null) {
//>>includeStart('debug', pragmas.debug);
dashCount = time.split(":").length - 1;
if (dashCount > 0 && dashCount !== 2 && dashCount !== 3) {
throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug')
hour = +tokens[1];
minute = +tokens[2];
second = +tokens[3];
millisecond = +(tokens[4] || 0) * 1000.0;
offsetIndex = 5;
} else {
tokens = time.match(matchHoursMinutes);
if (tokens !== null) {
//>>includeStart('debug', pragmas.debug);
dashCount = time.split(":").length - 1;
if (dashCount > 2) {
throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug')
hour = +tokens[1];
minute = +tokens[2];
second = +(tokens[3] || 0) * 60.0;
offsetIndex = 4;
} else {
tokens = time.match(matchHours);
if (tokens !== null) {
hour = +tokens[1];
minute = +(tokens[2] || 0) * 60.0;
offsetIndex = 3;
} else {
//>>includeStart('debug', pragmas.debug);
throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
//>>includeEnd('debug')
}
}
}
//Validate that all values are in proper range. Minutes and hours have special cases at 60 and 24.
//>>includeStart('debug', pragmas.debug);
if (
minute >= 60 ||
second >= 61 ||
hour > 24 ||
(hour === 24 && (minute > 0 || second > 0 || millisecond > 0))
) {
throw new RuntimeError.DeveloperError(iso8601ErrorMessage);
}
//>>includeEnd('debug');
//Check the UTC offset value, if no value exists, use local time
//a Z indicates UTC, + or - are offsets.
const offset = tokens[offsetIndex];
const offsetHours = +tokens[offsetIndex + 1];
const offsetMinutes = +(tokens[offsetIndex + 2] || 0);
switch (offset) {
case "+":
hour = hour - offsetHours;
minute = minute - offsetMinutes;
break;
case "-":
hour = hour + offsetHours;
minute = minute + offsetMinutes;
break;
case "Z":
break;
default:
minute =
minute +
new Date(
Date.UTC(year, month - 1, day, hour, minute)
).getTimezoneOffset();
break;
}
}
//ISO8601 denotes a leap second by any time having a seconds component of 60 seconds.
//If that's the case, we need to temporarily subtract a second in order to build a UTC date.
//Then we add it back in after converting to TAI.
const isLeapSecond = second === 60;
if (isLeapSecond) {
second--;
}
//Even if we successfully parsed the string into its components, after applying UTC offset or
//special cases like 24:00:00 denoting midnight, we need to normalize the data appropriately.
//milliseconds can never be greater than 1000, and seconds can't be above 60, so we start with minutes
while (minute >= 60) {
minute -= 60;
hour++;
}
while (hour >= 24) {
hour -= 24;
day++;
}
tmp = inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
while (day > tmp) {
day -= tmp;
month++;
if (month > 12) {
month -= 12;
year++;
}
tmp =
inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
}
//If UTC offset is at the beginning/end of the day, minutes can be negative.
while (minute < 0) {
minute += 60;
hour--;
}
while (hour < 0) {
hour += 24;
day--;
}
while (day < 1) {
month--;
if (month < 1) {
month += 12;
year--;
}
tmp =
inLeapYear && month === 2 ? daysInLeapFeburary : daysInMonth[month - 1];
day += tmp;
}
//Now create the JulianDate components from the Gregorian date and actually create our instance.
const components = computeJulianDateComponents(
year,
month,
day,
hour,
minute,
second,
millisecond
);
if (!when.defined(result)) {
result = new JulianDate(components[0], components[1], TimeStandard$1.UTC);
} else {
setComponents(components[0], components[1], result);
convertUtcToTai(result);
}
//If we were on a leap second, add it back.
if (isLeapSecond) {
JulianDate.addSeconds(result, 1, result);
}
return result;
};
/**
* Creates a new instance that represents the current system time.
* This is equivalent to calling JulianDate.fromDate(new Date());
.
*
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*/
JulianDate.now = function (result) {
return JulianDate.fromDate(new Date(), result);
};
const toGregorianDateScratch = new JulianDate(0, 0, TimeStandard$1.TAI);
/**
* Creates a {@link GregorianDate} from the provided instance.
*
* @param {JulianDate} julianDate The date to be converted.
* @param {GregorianDate} [result] An existing instance to use for the result.
* @returns {GregorianDate} The modified result parameter or a new instance if none was provided.
*/
JulianDate.toGregorianDate = function (julianDate, result) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(julianDate)) {
throw new RuntimeError.DeveloperError("julianDate is required.");
}
//>>includeEnd('debug');
let isLeapSecond = false;
let thisUtc = convertTaiToUtc(julianDate, toGregorianDateScratch);
if (!when.defined(thisUtc)) {
//Conversion to UTC will fail if we are during a leap second.
//If that's the case, subtract a second and convert again.
//JavaScript doesn't support leap seconds, so this results in second 59 being repeated twice.
JulianDate.addSeconds(julianDate, -1, toGregorianDateScratch);
thisUtc = convertTaiToUtc(toGregorianDateScratch, toGregorianDateScratch);
isLeapSecond = true;
}
let julianDayNumber = thisUtc.dayNumber;
const secondsOfDay = thisUtc.secondsOfDay;
if (secondsOfDay >= 43200.0) {
julianDayNumber += 1;
}
// Algorithm from page 604 of the Explanatory Supplement to the
// Astronomical Almanac (Seidelmann 1992).
let L = (julianDayNumber + 68569) | 0;
const N = ((4 * L) / 146097) | 0;
L = (L - (((146097 * N + 3) / 4) | 0)) | 0;
const I = ((4000 * (L + 1)) / 1461001) | 0;
L = (L - (((1461 * I) / 4) | 0) + 31) | 0;
const J = ((80 * L) / 2447) | 0;
const day = (L - (((2447 * J) / 80) | 0)) | 0;
L = (J / 11) | 0;
const month = (J + 2 - 12 * L) | 0;
const year = (100 * (N - 49) + I + L) | 0;
let hour = (secondsOfDay / TimeConstants$1.SECONDS_PER_HOUR) | 0;
let remainingSeconds = secondsOfDay - hour * TimeConstants$1.SECONDS_PER_HOUR;
const minute = (remainingSeconds / TimeConstants$1.SECONDS_PER_MINUTE) | 0;
remainingSeconds =
remainingSeconds - minute * TimeConstants$1.SECONDS_PER_MINUTE;
let second = remainingSeconds | 0;
const millisecond =
(remainingSeconds - second) / TimeConstants$1.SECONDS_PER_MILLISECOND;
// JulianDates are noon-based
hour += 12;
if (hour > 23) {
hour -= 24;
}
//If we were on a leap second, add it back.
if (isLeapSecond) {
second += 1;
}
if (!when.defined(result)) {
return new GregorianDate(
year,
month,
day,
hour,
minute,
second,
millisecond,
isLeapSecond
);
}
result.year = year;
result.month = month;
result.day = day;
result.hour = hour;
result.minute = minute;
result.second = second;
result.millisecond = millisecond;
result.isLeapSecond = isLeapSecond;
return result;
};
/**
* Creates a JavaScript Date from the provided instance.
* Since JavaScript dates are only accurate to the nearest millisecond and
* cannot represent a leap second, consider using {@link JulianDate.toGregorianDate} instead.
* If the provided JulianDate is during a leap second, the previous second is used.
*
* @param {JulianDate} julianDate The date to be converted.
* @returns {Date} A new instance representing the provided date.
*/
JulianDate.toDate = function (julianDate) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(julianDate)) {
throw new RuntimeError.DeveloperError("julianDate is required.");
}
//>>includeEnd('debug');
const gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
let second = gDate.second;
if (gDate.isLeapSecond) {
second -= 1;
}
return new Date(
Date.UTC(
gDate.year,
gDate.month - 1,
gDate.day,
gDate.hour,
gDate.minute,
second,
gDate.millisecond
)
);
};
/**
* Creates an ISO8601 representation of the provided date.
*
* @param {JulianDate} julianDate The date to be converted.
* @param {Number} [precision] The number of fractional digits used to represent the seconds component. By default, the most precise representation is used.
* @returns {String} The ISO8601 representation of the provided date.
*/
JulianDate.toIso8601 = function (julianDate, precision) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(julianDate)) {
throw new RuntimeError.DeveloperError("julianDate is required.");
}
//>>includeEnd('debug');
const gDate = JulianDate.toGregorianDate(julianDate, gregorianDateScratch);
let year = gDate.year;
let month = gDate.month;
let day = gDate.day;
let hour = gDate.hour;
const minute = gDate.minute;
const second = gDate.second;
const millisecond = gDate.millisecond;
// special case - Iso8601.MAXIMUM_VALUE produces a string which we can't parse unless we adjust.
// 10000-01-01T00:00:00 is the same instant as 9999-12-31T24:00:00
if (
year === 10000 &&
month === 1 &&
day === 1 &&
hour === 0 &&
minute === 0 &&
second === 0 &&
millisecond === 0
) {
year = 9999;
month = 12;
day = 31;
hour = 24;
}
let millisecondStr;
if (!when.defined(precision) && millisecond !== 0) {
//Forces milliseconds into a number with at least 3 digits to whatever the default toString() precision is.
millisecondStr = (millisecond * 0.01).toString().replace(".", "");
return `${year.toString().padStart(4, "0")}-${month
.toString()
.padStart(2, "0")}-${day
.toString()
.padStart(2, "0")}T${hour
.toString()
.padStart(2, "0")}:${minute
.toString()
.padStart(2, "0")}:${second
.toString()
.padStart(2, "0")}.${millisecondStr}Z`;
}
//Precision is either 0 or milliseconds is 0 with undefined precision, in either case, leave off milliseconds entirely
if (!when.defined(precision) || precision === 0) {
return `${year.toString().padStart(4, "0")}-${month
.toString()
.padStart(2, "0")}-${day
.toString()
.padStart(2, "0")}T${hour
.toString()
.padStart(2, "0")}:${minute
.toString()
.padStart(2, "0")}:${second.toString().padStart(2, "0")}Z`;
}
//Forces milliseconds into a number with at least 3 digits to whatever the specified precision is.
millisecondStr = (millisecond * 0.01)
.toFixed(precision)
.replace(".", "")
.slice(0, precision);
return `${year.toString().padStart(4, "0")}-${month
.toString()
.padStart(2, "0")}-${day
.toString()
.padStart(2, "0")}T${hour
.toString()
.padStart(2, "0")}:${minute
.toString()
.padStart(2, "0")}:${second
.toString()
.padStart(2, "0")}.${millisecondStr}Z`;
};
/**
* Duplicates a JulianDate instance.
*
* @param {JulianDate} julianDate The date to duplicate.
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided. Returns undefined if julianDate is undefined.
*/
JulianDate.clone = function (julianDate, result) {
if (!when.defined(julianDate)) {
return undefined;
}
if (!when.defined(result)) {
return new JulianDate(
julianDate.dayNumber,
julianDate.secondsOfDay,
TimeStandard$1.TAI
);
}
result.dayNumber = julianDate.dayNumber;
result.secondsOfDay = julianDate.secondsOfDay;
return result;
};
/**
* Compares two instances.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {Number} A negative value if left is less than right, a positive value if left is greater than right, or zero if left and right are equal.
*/
JulianDate.compare = function (left, right) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(left)) {
throw new RuntimeError.DeveloperError("left is required.");
}
if (!when.defined(right)) {
throw new RuntimeError.DeveloperError("right is required.");
}
//>>includeEnd('debug');
const julianDayNumberDifference = left.dayNumber - right.dayNumber;
if (julianDayNumberDifference !== 0) {
return julianDayNumberDifference;
}
return left.secondsOfDay - right.secondsOfDay;
};
/**
* Compares two instances and returns true
if they are equal, false
otherwise.
*
* @param {JulianDate} [left] The first instance.
* @param {JulianDate} [right] The second instance.
* @returns {Boolean} true
if the dates are equal; otherwise, false
.
*/
JulianDate.equals = function (left, right) {
return (
left === right ||
(when.defined(left) &&
when.defined(right) &&
left.dayNumber === right.dayNumber &&
left.secondsOfDay === right.secondsOfDay)
);
};
/**
* Compares two instances and returns true
if they are within epsilon
seconds of
* each other. That is, in order for the dates to be considered equal (and for
* this function to return true
), the absolute value of the difference between them, in
* seconds, must be less than epsilon
.
*
* @param {JulianDate} [left] The first instance.
* @param {JulianDate} [right] The second instance.
* @param {Number} [epsilon=0] The maximum number of seconds that should separate the two instances.
* @returns {Boolean} true
if the two dates are within epsilon
seconds of each other; otherwise false
.
*/
JulianDate.equalsEpsilon = function (left, right, epsilon) {
epsilon = when.defaultValue(epsilon, 0);
return (
left === right ||
(when.defined(left) &&
when.defined(right) &&
Math.abs(JulianDate.secondsDifference(left, right)) <= epsilon)
);
};
/**
* Computes the total number of whole and fractional days represented by the provided instance.
*
* @param {JulianDate} julianDate The date.
* @returns {Number} The Julian date as single floating point number.
*/
JulianDate.totalDays = function (julianDate) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(julianDate)) {
throw new RuntimeError.DeveloperError("julianDate is required.");
}
//>>includeEnd('debug');
return (
julianDate.dayNumber +
julianDate.secondsOfDay / TimeConstants$1.SECONDS_PER_DAY
);
};
/**
* Computes the difference in seconds between the provided instance.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {Number} The difference, in seconds, when subtracting right
from left
.
*/
JulianDate.secondsDifference = function (left, right) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(left)) {
throw new RuntimeError.DeveloperError("left is required.");
}
if (!when.defined(right)) {
throw new RuntimeError.DeveloperError("right is required.");
}
//>>includeEnd('debug');
const dayDifference =
(left.dayNumber - right.dayNumber) * TimeConstants$1.SECONDS_PER_DAY;
return dayDifference + (left.secondsOfDay - right.secondsOfDay);
};
/**
* Computes the difference in days between the provided instance.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {Number} The difference, in days, when subtracting right
from left
.
*/
JulianDate.daysDifference = function (left, right) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(left)) {
throw new RuntimeError.DeveloperError("left is required.");
}
if (!when.defined(right)) {
throw new RuntimeError.DeveloperError("right is required.");
}
//>>includeEnd('debug');
const dayDifference = left.dayNumber - right.dayNumber;
const secondDifference =
(left.secondsOfDay - right.secondsOfDay) / TimeConstants$1.SECONDS_PER_DAY;
return dayDifference + secondDifference;
};
/**
* Computes the number of seconds the provided instance is ahead of UTC.
*
* @param {JulianDate} julianDate The date.
* @returns {Number} The number of seconds the provided instance is ahead of UTC
*/
JulianDate.computeTaiMinusUtc = function (julianDate) {
binarySearchScratchLeapSecond.julianDate = julianDate;
const leapSeconds = JulianDate.leapSeconds;
let index = binarySearch(
leapSeconds,
binarySearchScratchLeapSecond,
compareLeapSecondDates$1
);
if (index < 0) {
index = ~index;
--index;
if (index < 0) {
index = 0;
}
}
return leapSeconds[index].offset;
};
/**
* Adds the provided number of seconds to the provided date instance.
*
* @param {JulianDate} julianDate The date.
* @param {Number} seconds The number of seconds to add or subtract.
* @param {JulianDate} result An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter.
*/
JulianDate.addSeconds = function (julianDate, seconds, result) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(julianDate)) {
throw new RuntimeError.DeveloperError("julianDate is required.");
}
if (!when.defined(seconds)) {
throw new RuntimeError.DeveloperError("seconds is required.");
}
if (!when.defined(result)) {
throw new RuntimeError.DeveloperError("result is required.");
}
//>>includeEnd('debug');
return setComponents(
julianDate.dayNumber,
julianDate.secondsOfDay + seconds,
result
);
};
/**
* Adds the provided number of minutes to the provided date instance.
*
* @param {JulianDate} julianDate The date.
* @param {Number} minutes The number of minutes to add or subtract.
* @param {JulianDate} result An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter.
*/
JulianDate.addMinutes = function (julianDate, minutes, result) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(julianDate)) {
throw new RuntimeError.DeveloperError("julianDate is required.");
}
if (!when.defined(minutes)) {
throw new RuntimeError.DeveloperError("minutes is required.");
}
if (!when.defined(result)) {
throw new RuntimeError.DeveloperError("result is required.");
}
//>>includeEnd('debug');
const newSecondsOfDay =
julianDate.secondsOfDay + minutes * TimeConstants$1.SECONDS_PER_MINUTE;
return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
};
/**
* Adds the provided number of hours to the provided date instance.
*
* @param {JulianDate} julianDate The date.
* @param {Number} hours The number of hours to add or subtract.
* @param {JulianDate} result An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter.
*/
JulianDate.addHours = function (julianDate, hours, result) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(julianDate)) {
throw new RuntimeError.DeveloperError("julianDate is required.");
}
if (!when.defined(hours)) {
throw new RuntimeError.DeveloperError("hours is required.");
}
if (!when.defined(result)) {
throw new RuntimeError.DeveloperError("result is required.");
}
//>>includeEnd('debug');
const newSecondsOfDay =
julianDate.secondsOfDay + hours * TimeConstants$1.SECONDS_PER_HOUR;
return setComponents(julianDate.dayNumber, newSecondsOfDay, result);
};
/**
* Adds the provided number of days to the provided date instance.
*
* @param {JulianDate} julianDate The date.
* @param {Number} days The number of days to add or subtract.
* @param {JulianDate} result An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter.
*/
JulianDate.addDays = function (julianDate, days, result) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(julianDate)) {
throw new RuntimeError.DeveloperError("julianDate is required.");
}
if (!when.defined(days)) {
throw new RuntimeError.DeveloperError("days is required.");
}
if (!when.defined(result)) {
throw new RuntimeError.DeveloperError("result is required.");
}
//>>includeEnd('debug');
const newJulianDayNumber = julianDate.dayNumber + days;
return setComponents(newJulianDayNumber, julianDate.secondsOfDay, result);
};
/**
* Compares the provided instances and returns true
if left
is earlier than right
, false
otherwise.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {Boolean} true
if left
is earlier than right
, false
otherwise.
*/
JulianDate.lessThan = function (left, right) {
return JulianDate.compare(left, right) < 0;
};
/**
* Compares the provided instances and returns true
if left
is earlier than or equal to right
, false
otherwise.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {Boolean} true
if left
is earlier than or equal to right
, false
otherwise.
*/
JulianDate.lessThanOrEquals = function (left, right) {
return JulianDate.compare(left, right) <= 0;
};
/**
* Compares the provided instances and returns true
if left
is later than right
, false
otherwise.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {Boolean} true
if left
is later than right
, false
otherwise.
*/
JulianDate.greaterThan = function (left, right) {
return JulianDate.compare(left, right) > 0;
};
/**
* Compares the provided instances and returns true
if left
is later than or equal to right
, false
otherwise.
*
* @param {JulianDate} left The first instance.
* @param {JulianDate} right The second instance.
* @returns {Boolean} true
if left
is later than or equal to right
, false
otherwise.
*/
JulianDate.greaterThanOrEquals = function (left, right) {
return JulianDate.compare(left, right) >= 0;
};
/**
* Duplicates this instance.
*
* @param {JulianDate} [result] An existing instance to use for the result.
* @returns {JulianDate} The modified result parameter or a new instance if none was provided.
*/
JulianDate.prototype.clone = function (result) {
return JulianDate.clone(this, result);
};
/**
* Compares this and the provided instance and returns true
if they are equal, false
otherwise.
*
* @param {JulianDate} [right] The second instance.
* @returns {Boolean} true
if the dates are equal; otherwise, false
.
*/
JulianDate.prototype.equals = function (right) {
return JulianDate.equals(this, right);
};
/**
* Compares this and the provided instance and returns true
if they are within epsilon
seconds of
* each other. That is, in order for the dates to be considered equal (and for
* this function to return true
), the absolute value of the difference between them, in
* seconds, must be less than epsilon
.
*
* @param {JulianDate} [right] The second instance.
* @param {Number} [epsilon=0] The maximum number of seconds that should separate the two instances.
* @returns {Boolean} true
if the two dates are within epsilon
seconds of each other; otherwise false
.
*/
JulianDate.prototype.equalsEpsilon = function (right, epsilon) {
return JulianDate.equalsEpsilon(this, right, epsilon);
};
/**
* Creates a string representing this date in ISO8601 format.
*
* @returns {String} A string representing this date in ISO8601 format.
*/
JulianDate.prototype.toString = function () {
return JulianDate.toIso8601(this);
};
/**
* Gets or sets the list of leap seconds used throughout Cesium.
* @memberof JulianDate
* @type {LeapSecond[]}
*/
JulianDate.leapSeconds = [
new LeapSecond(new JulianDate(2441317, 43210.0, TimeStandard$1.TAI), 10), // January 1, 1972 00:00:00 UTC
new LeapSecond(new JulianDate(2441499, 43211.0, TimeStandard$1.TAI), 11), // July 1, 1972 00:00:00 UTC
new LeapSecond(new JulianDate(2441683, 43212.0, TimeStandard$1.TAI), 12), // January 1, 1973 00:00:00 UTC
new LeapSecond(new JulianDate(2442048, 43213.0, TimeStandard$1.TAI), 13), // January 1, 1974 00:00:00 UTC
new LeapSecond(new JulianDate(2442413, 43214.0, TimeStandard$1.TAI), 14), // January 1, 1975 00:00:00 UTC
new LeapSecond(new JulianDate(2442778, 43215.0, TimeStandard$1.TAI), 15), // January 1, 1976 00:00:00 UTC
new LeapSecond(new JulianDate(2443144, 43216.0, TimeStandard$1.TAI), 16), // January 1, 1977 00:00:00 UTC
new LeapSecond(new JulianDate(2443509, 43217.0, TimeStandard$1.TAI), 17), // January 1, 1978 00:00:00 UTC
new LeapSecond(new JulianDate(2443874, 43218.0, TimeStandard$1.TAI), 18), // January 1, 1979 00:00:00 UTC
new LeapSecond(new JulianDate(2444239, 43219.0, TimeStandard$1.TAI), 19), // January 1, 1980 00:00:00 UTC
new LeapSecond(new JulianDate(2444786, 43220.0, TimeStandard$1.TAI), 20), // July 1, 1981 00:00:00 UTC
new LeapSecond(new JulianDate(2445151, 43221.0, TimeStandard$1.TAI), 21), // July 1, 1982 00:00:00 UTC
new LeapSecond(new JulianDate(2445516, 43222.0, TimeStandard$1.TAI), 22), // July 1, 1983 00:00:00 UTC
new LeapSecond(new JulianDate(2446247, 43223.0, TimeStandard$1.TAI), 23), // July 1, 1985 00:00:00 UTC
new LeapSecond(new JulianDate(2447161, 43224.0, TimeStandard$1.TAI), 24), // January 1, 1988 00:00:00 UTC
new LeapSecond(new JulianDate(2447892, 43225.0, TimeStandard$1.TAI), 25), // January 1, 1990 00:00:00 UTC
new LeapSecond(new JulianDate(2448257, 43226.0, TimeStandard$1.TAI), 26), // January 1, 1991 00:00:00 UTC
new LeapSecond(new JulianDate(2448804, 43227.0, TimeStandard$1.TAI), 27), // July 1, 1992 00:00:00 UTC
new LeapSecond(new JulianDate(2449169, 43228.0, TimeStandard$1.TAI), 28), // July 1, 1993 00:00:00 UTC
new LeapSecond(new JulianDate(2449534, 43229.0, TimeStandard$1.TAI), 29), // July 1, 1994 00:00:00 UTC
new LeapSecond(new JulianDate(2450083, 43230.0, TimeStandard$1.TAI), 30), // January 1, 1996 00:00:00 UTC
new LeapSecond(new JulianDate(2450630, 43231.0, TimeStandard$1.TAI), 31), // July 1, 1997 00:00:00 UTC
new LeapSecond(new JulianDate(2451179, 43232.0, TimeStandard$1.TAI), 32), // January 1, 1999 00:00:00 UTC
new LeapSecond(new JulianDate(2453736, 43233.0, TimeStandard$1.TAI), 33), // January 1, 2006 00:00:00 UTC
new LeapSecond(new JulianDate(2454832, 43234.0, TimeStandard$1.TAI), 34), // January 1, 2009 00:00:00 UTC
new LeapSecond(new JulianDate(2456109, 43235.0, TimeStandard$1.TAI), 35), // July 1, 2012 00:00:00 UTC
new LeapSecond(new JulianDate(2457204, 43236.0, TimeStandard$1.TAI), 36), // July 1, 2015 00:00:00 UTC
new LeapSecond(new JulianDate(2457754, 43237.0, TimeStandard$1.TAI), 37), // January 1, 2017 00:00:00 UTC
];
/* This file is automatically rebuilt by the Cesium build process. */
var punycode = when.createCommonjsModule(function (module, exports) {
(function(root) {
/** Detect free variables */
var freeExports = exports &&
!exports.nodeType && exports;
var freeModule = module &&
!module.nodeType && module;
var freeGlobal = typeof when.commonjsGlobal == 'object' && when.commonjsGlobal;
if (
freeGlobal.global === freeGlobal ||
freeGlobal.window === freeGlobal ||
freeGlobal.self === freeGlobal
) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see true
is preferable for requests going through HTTP/1 servers.
*
* @type {Boolean}
* @readonly
*
* @default false
*/
this.throttleByServer = throttleByServer;
/**
* Type of request.
*
* @type {RequestType}
* @readonly
*
* @default RequestType.OTHER
*/
this.type = when.defaultValue(options.type, RequestType$1.OTHER);
/**
* A key used to identify the server that a request is going to. It is derived from the url's authority and scheme.
*
* @type {String}
*
* @private
*/
this.serverKey = undefined;
/**
* The current state of the request.
*
* @type {RequestState}
* @readonly
*/
this.state = RequestState$1.UNISSUED;
/**
* The requests's deferred promise.
*
* @type {Object}
*
* @private
*/
this.deferred = undefined;
/**
* Whether the request was explicitly cancelled.
*
* @type {Boolean}
*
* @private
*/
this.cancelled = false;
}
/**
* Mark the request as cancelled.
*
* @private
*/
Request.prototype.cancel = function () {
this.cancelled = true;
};
/**
* Duplicates a Request instance.
*
* @param {Request} [result] The object onto which to store the result.
*
* @returns {Request} The modified result parameter or a new Resource instance if one was not provided.
*/
Request.prototype.clone = function (result) {
if (!when.defined(result)) {
return new Request(this);
}
result.url = this.url;
result.requestFunction = this.requestFunction;
result.cancelFunction = this.cancelFunction;
result.priorityFunction = this.priorityFunction;
result.priority = this.priority;
result.throttle = this.throttle;
result.throttleByServer = this.throttleByServer;
result.type = this.type;
result.serverKey = this.serverKey;
// These get defaulted because the cloned request hasn't been issued
result.state = this.RequestState.UNISSUED;
result.deferred = undefined;
result.cancelled = false;
return result;
};
/**
* Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
* a dictionary.
*
* @function parseResponseHeaders
*
* @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
* described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
* @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
* is that header's value.
*
* @private
*/
function parseResponseHeaders(headerString) {
const headers = {};
if (!headerString) {
return headers;
}
const headerPairs = headerString.split("\u000d\u000a");
for (let i = 0; i < headerPairs.length; ++i) {
const headerPair = headerPairs[i];
// Can't use split() here because it does the wrong thing
// if the header value has the string ": " in it.
const index = headerPair.indexOf("\u003a\u0020");
if (index > 0) {
const key = headerPair.substring(0, index);
const val = headerPair.substring(index + 2);
headers[key] = val;
}
}
return headers;
}
/**
* An event that is raised when a request encounters an error.
*
* @constructor
* @alias RequestErrorEvent
*
* @param {Number} [statusCode] The HTTP error status code, such as 404.
* @param {Object} [response] The response included along with the error.
* @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
* string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
*/
function RequestErrorEvent(statusCode, response, responseHeaders) {
/**
* The HTTP error status code, such as 404. If the error does not have a particular
* HTTP code, this property will be undefined.
*
* @type {Number}
*/
this.statusCode = statusCode;
/**
* The response included along with the error. If the error does not include a response,
* this property will be undefined.
*
* @type {Object}
*/
this.response = response;
/**
* The headers included in the response, represented as an object literal of key/value pairs.
* If the error does not include any headers, this property will be undefined.
*
* @type {Object}
*/
this.responseHeaders = responseHeaders;
if (typeof this.responseHeaders === "string") {
this.responseHeaders = parseResponseHeaders(this.responseHeaders);
}
}
/**
* Creates a string representing this RequestErrorEvent.
* @memberof RequestErrorEvent
*
* @returns {String} A string representing the provided RequestErrorEvent.
*/
RequestErrorEvent.prototype.toString = function () {
let str = "Request has failed.";
if (when.defined(this.statusCode)) {
str += ` Status Code: ${this.statusCode}`;
}
return str;
};
/**
* A generic utility class for managing subscribers for a particular event.
* This class is usually instantiated inside of a container class and
* exposed as a property for others to subscribe to.
*
* @alias Event
* @constructor
* @example
* MyObject.prototype.myListener = function(arg1, arg2) {
* this.myArg1Copy = arg1;
* this.myArg2Copy = arg2;
* }
*
* const myObjectInstance = new MyObject();
* const evt = new Cesium.Event();
* evt.addEventListener(MyObject.prototype.myListener, myObjectInstance);
* evt.raiseEvent('1', '2');
* evt.removeEventListener(MyObject.prototype.myListener);
*/
function Event() {
this._listeners = [];
this._scopes = [];
this._toRemove = [];
this._insideRaiseEvent = false;
}
Object.defineProperties(Event.prototype, {
/**
* The number of listeners currently subscribed to the event.
* @memberof Event.prototype
* @type {Number}
* @readonly
*/
numberOfListeners: {
get: function () {
return this._listeners.length - this._toRemove.length;
},
},
});
/**
* Registers a callback function to be executed whenever the event is raised.
* An optional scope can be provided to serve as the this
pointer
* in which the function will execute.
*
* @param {Function} listener The function to be executed when the event is raised.
* @param {Object} [scope] An optional object scope to serve as the this
* pointer in which the listener function will execute.
* @returns {Event.RemoveCallback} A function that will remove this event listener when invoked.
*
* @see Event#raiseEvent
* @see Event#removeEventListener
*/
Event.prototype.addEventListener = function (listener, scope) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.func("listener", listener);
//>>includeEnd('debug');
this._listeners.push(listener);
this._scopes.push(scope);
const event = this;
return function () {
event.removeEventListener(listener, scope);
};
};
/**
* Unregisters a previously registered callback.
*
* @param {Function} listener The function to be unregistered.
* @param {Object} [scope] The scope that was originally passed to addEventListener.
* @returns {Boolean} true
if the listener was removed; false
if the listener and scope are not registered with the event.
*
* @see Event#addEventListener
* @see Event#raiseEvent
*/
Event.prototype.removeEventListener = function (listener, scope) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.func("listener", listener);
//>>includeEnd('debug');
const listeners = this._listeners;
const scopes = this._scopes;
let index = -1;
for (let i = 0; i < listeners.length; i++) {
if (listeners[i] === listener && scopes[i] === scope) {
index = i;
break;
}
}
if (index !== -1) {
if (this._insideRaiseEvent) {
//In order to allow removing an event subscription from within
//a callback, we don't actually remove the items here. Instead
//remember the index they are at and undefined their value.
this._toRemove.push(index);
listeners[index] = undefined;
scopes[index] = undefined;
} else {
listeners.splice(index, 1);
scopes.splice(index, 1);
}
return true;
}
return false;
};
function compareNumber(a, b) {
return b - a;
}
/**
* Raises the event by calling each registered listener with all supplied arguments.
*
* @param {...Object} arguments This method takes any number of parameters and passes them through to the listener functions.
*
* @see Event#addEventListener
* @see Event#removeEventListener
*/
Event.prototype.raiseEvent = function () {
this._insideRaiseEvent = true;
let i;
const listeners = this._listeners;
const scopes = this._scopes;
let length = listeners.length;
for (i = 0; i < length; i++) {
const listener = listeners[i];
if (when.defined(listener)) {
listeners[i].apply(scopes[i], arguments);
}
}
//Actually remove items removed in removeEventListener.
const toRemove = this._toRemove;
length = toRemove.length;
if (length > 0) {
toRemove.sort(compareNumber);
for (i = 0; i < length; i++) {
const index = toRemove[i];
listeners.splice(index, 1);
scopes.splice(index, 1);
}
toRemove.length = 0;
}
this._insideRaiseEvent = false;
};
/**
* Array implementation of a heap.
*
* @alias Heap
* @constructor
* @private
*
* @param {Object} options Object with the following properties:
* @param {Heap.ComparatorCallback} options.comparator The comparator to use for the heap. If comparator(a, b) is less than 0, sort a to a lower index than b, otherwise sort to a higher index.
*/
function Heap(options) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("options", options);
RuntimeError.Check.defined("options.comparator", options.comparator);
//>>includeEnd('debug');
this._comparator = options.comparator;
this._array = [];
this._length = 0;
this._maximumLength = undefined;
}
Object.defineProperties(Heap.prototype, {
/**
* Gets the length of the heap.
*
* @memberof Heap.prototype
*
* @type {Number}
* @readonly
*/
length: {
get: function () {
return this._length;
},
},
/**
* Gets the internal array.
*
* @memberof Heap.prototype
*
* @type {Array}
* @readonly
*/
internalArray: {
get: function () {
return this._array;
},
},
/**
* Gets and sets the maximum length of the heap.
*
* @memberof Heap.prototype
*
* @type {Number}
*/
maximumLength: {
get: function () {
return this._maximumLength;
},
set: function (value) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.number.greaterThanOrEquals("maximumLength", value, 0);
//>>includeEnd('debug');
const originalLength = this._length;
if (value < originalLength) {
const array = this._array;
// Remove trailing references
for (let i = value; i < originalLength; ++i) {
array[i] = undefined;
}
this._length = value;
array.length = value;
}
this._maximumLength = value;
},
},
/**
* The comparator to use for the heap. If comparator(a, b) is less than 0, sort a to a lower index than b, otherwise sort to a higher index.
*
* @memberof Heap.prototype
*
* @type {Heap.ComparatorCallback}
*/
comparator: {
get: function () {
return this._comparator;
},
},
});
function swap(array, a, b) {
const temp = array[a];
array[a] = array[b];
array[b] = temp;
}
/**
* Resizes the internal array of the heap.
*
* @param {Number} [length] The length to resize internal array to. Defaults to the current length of the heap.
*/
Heap.prototype.reserve = function (length) {
length = when.defaultValue(length, this._length);
this._array.length = length;
};
/**
* Update the heap so that index and all descendants satisfy the heap property.
*
* @param {Number} [index=0] The starting index to heapify from.
*/
Heap.prototype.heapify = function (index) {
index = when.defaultValue(index, 0);
const length = this._length;
const comparator = this._comparator;
const array = this._array;
let candidate = -1;
let inserting = true;
while (inserting) {
const right = 2 * (index + 1);
const left = right - 1;
if (left < length && comparator(array[left], array[index]) < 0) {
candidate = left;
} else {
candidate = index;
}
if (right < length && comparator(array[right], array[candidate]) < 0) {
candidate = right;
}
if (candidate !== index) {
swap(array, candidate, index);
index = candidate;
} else {
inserting = false;
}
}
};
/**
* Resort the heap.
*/
Heap.prototype.resort = function () {
const length = this._length;
for (let i = Math.ceil(length / 2); i >= 0; --i) {
this.heapify(i);
}
};
/**
* Insert an element into the heap. If the length would grow greater than maximumLength
* of the heap, extra elements are removed.
*
* @param {*} element The element to insert
*
* @return {*} The element that was removed from the heap if the heap is at full capacity.
*/
Heap.prototype.insert = function (element) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.defined("element", element);
//>>includeEnd('debug');
const array = this._array;
const comparator = this._comparator;
const maximumLength = this._maximumLength;
let index = this._length++;
if (index < array.length) {
array[index] = element;
} else {
array.push(element);
}
while (index !== 0) {
const parent = Math.floor((index - 1) / 2);
if (comparator(array[index], array[parent]) < 0) {
swap(array, index, parent);
index = parent;
} else {
break;
}
}
let removedElement;
if (when.defined(maximumLength) && this._length > maximumLength) {
removedElement = array[maximumLength];
this._length = maximumLength;
}
return removedElement;
};
/**
* Remove the element specified by index from the heap and return it.
*
* @param {Number} [index=0] The index to remove.
* @returns {*} The specified element of the heap.
*/
Heap.prototype.pop = function (index) {
index = when.defaultValue(index, 0);
if (this._length === 0) {
return undefined;
}
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.number.lessThan("index", index, this._length);
//>>includeEnd('debug');
const array = this._array;
const root = array[index];
swap(array, index, --this._length);
this.heapify(index);
array[this._length] = undefined; // Remove trailing reference
return root;
};
function sortRequests(a, b) {
return a.priority - b.priority;
}
const statistics = {
numberOfAttemptedRequests: 0,
numberOfActiveRequests: 0,
numberOfCancelledRequests: 0,
numberOfCancelledActiveRequests: 0,
numberOfFailedRequests: 0,
numberOfActiveRequestsEver: 0,
lastNumberOfActiveRequests: 0,
};
let priorityHeapLength = 20;
const requestHeap = new Heap({
comparator: sortRequests,
});
requestHeap.maximumLength = priorityHeapLength;
requestHeap.reserve(priorityHeapLength);
const activeRequests = [];
let numberOfActiveRequestsByServer = {};
const pageUri =
typeof document !== "undefined" ? new URI(document.location.href) : new URI();
const requestCompletedEvent = new Event();
/**
* The request scheduler is used to track and constrain the number of active requests in order to prioritize incoming requests. The ability
* to retain control over the number of requests in CesiumJS is important because due to events such as changes in the camera position,
* a lot of new requests may be generated and a lot of in-flight requests may become redundant. The request scheduler manually constrains the
* number of requests so that newer requests wait in a shorter queue and don't have to compete for bandwidth with requests that have expired.
*
* @namespace RequestScheduler
*
*/
function RequestScheduler() {}
/**
* The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit.
* @type {Number}
* @default 50
*/
RequestScheduler.maximumRequests = 50;
/**
* The maximum number of simultaneous active requests per server. Un-throttled requests or servers specifically
* listed in {@link requestsByServer} do not observe this limit.
* @type {Number}
* @default 6
*/
RequestScheduler.maximumRequestsPerServer = 6;
/**
* A per server key list of overrides to use for throttling instead of maximumRequestsPerServer
* @type {Object}
*
* @example
* RequestScheduler.requestsByServer = {
* 'api.cesium.com:443': 18,
* 'assets.cesium.com:443': 18
* };
*/
RequestScheduler.requestsByServer = {
"api.cesium.com:443": 18,
"assets.cesium.com:443": 18,
};
/**
* Specifies if the request scheduler should throttle incoming requests, or let the browser queue requests under its control.
* @type {Boolean}
* @default true
*/
RequestScheduler.throttleRequests = true;
/**
* When true, log statistics to the console every frame
* @type {Boolean}
* @default false
* @private
*/
RequestScheduler.debugShowStatistics = false;
/**
* An event that's raised when a request is completed. Event handlers are passed
* the error object if the request fails.
*
* @type {Event}
* @default Event()
* @private
*/
RequestScheduler.requestCompletedEvent = requestCompletedEvent;
Object.defineProperties(RequestScheduler, {
/**
* Returns the statistics used by the request scheduler.
*
* @memberof RequestScheduler
*
* @type Object
* @readonly
* @private
*/
statistics: {
get: function () {
return statistics;
},
},
/**
* The maximum size of the priority heap. This limits the number of requests that are sorted by priority. Only applies to requests that are not yet active.
*
* @memberof RequestScheduler
*
* @type {Number}
* @default 20
* @private
*/
priorityHeapLength: {
get: function () {
return priorityHeapLength;
},
set: function (value) {
// If the new length shrinks the heap, need to cancel some of the requests.
// Since this value is not intended to be tweaked regularly it is fine to just cancel the high priority requests.
if (value < priorityHeapLength) {
while (requestHeap.length > value) {
const request = requestHeap.pop();
cancelRequest(request);
}
}
priorityHeapLength = value;
requestHeap.maximumLength = value;
requestHeap.reserve(value);
},
},
});
function updatePriority(request) {
if (when.defined(request.priorityFunction)) {
request.priority = request.priorityFunction();
}
}
/**
* Check if there are open slots for a particular server key. If desiredRequests is greater than 1, this checks if the queue has room for scheduling multiple requests.
* @param {String} serverKey The server key returned by {@link RequestScheduler.getServerKey}.
* @param {Number} [desiredRequests=1] How many requests the caller plans to request
* @return {Boolean} True if there are enough open slots for desiredRequests
more requests.
* @private
*/
RequestScheduler.serverHasOpenSlots = function (serverKey, desiredRequests) {
desiredRequests = when.defaultValue(desiredRequests, 1);
const maxRequests = when.defaultValue(
RequestScheduler.requestsByServer[serverKey],
RequestScheduler.maximumRequestsPerServer
);
const hasOpenSlotsServer =
numberOfActiveRequestsByServer[serverKey] + desiredRequests <= maxRequests;
return hasOpenSlotsServer;
};
/**
* Check if the priority heap has open slots, regardless of which server they
* are from. This is used in {@link Multiple3DTileContent} for determining when
* all requests can be scheduled
* @param {Number} desiredRequests The number of requests the caller intends to make
* @return {Boolean} true
if the heap has enough available slots to meet the desiredRequests. false
otherwise.
*
* @private
*/
RequestScheduler.heapHasOpenSlots = function (desiredRequests) {
const hasOpenSlotsHeap =
requestHeap.length + desiredRequests <= priorityHeapLength;
return hasOpenSlotsHeap;
};
function issueRequest(request) {
if (request.state === RequestState$1.UNISSUED) {
request.state = RequestState$1.ISSUED;
request.deferred = when.when.defer();
}
return request.deferred.promise;
}
function getRequestReceivedFunction(request) {
return function (results) {
if (request.state === RequestState$1.CANCELLED) {
// If the data request comes back but the request is cancelled, ignore it.
return;
}
// explicitly set to undefined to ensure GC of request response data. See #8843
const deferred = request.deferred;
--statistics.numberOfActiveRequests;
--numberOfActiveRequestsByServer[request.serverKey];
requestCompletedEvent.raiseEvent();
request.state = RequestState$1.RECEIVED;
request.deferred = undefined;
deferred.resolve(results);
};
}
function getRequestFailedFunction(request) {
return function (error) {
if (request.state === RequestState$1.CANCELLED) {
// If the data request comes back but the request is cancelled, ignore it.
return;
}
++statistics.numberOfFailedRequests;
--statistics.numberOfActiveRequests;
--numberOfActiveRequestsByServer[request.serverKey];
requestCompletedEvent.raiseEvent(error);
request.state = RequestState$1.FAILED;
request.deferred.reject(error);
};
}
function startRequest(request) {
const promise = issueRequest(request);
request.state = RequestState$1.ACTIVE;
activeRequests.push(request);
++statistics.numberOfActiveRequests;
++statistics.numberOfActiveRequestsEver;
++numberOfActiveRequestsByServer[request.serverKey];
request
.requestFunction()
.then(getRequestReceivedFunction(request))
.otherwise(getRequestFailedFunction(request));
return promise;
}
function cancelRequest(request) {
const active = request.state === RequestState$1.ACTIVE;
request.state = RequestState$1.CANCELLED;
++statistics.numberOfCancelledRequests;
// check that deferred has not been cleared since cancelRequest can be called
// on a finished request, e.g. by clearForSpecs during tests
if (when.defined(request.deferred)) {
const deferred = request.deferred;
request.deferred = undefined;
deferred.reject();
}
if (active) {
--statistics.numberOfActiveRequests;
--numberOfActiveRequestsByServer[request.serverKey];
++statistics.numberOfCancelledActiveRequests;
}
if (when.defined(request.cancelFunction)) {
request.cancelFunction();
}
}
/**
* Sort requests by priority and start requests.
* @private
*/
RequestScheduler.update = function () {
let i;
let request;
// Loop over all active requests. Cancelled, failed, or received requests are removed from the array to make room for new requests.
let removeCount = 0;
const activeLength = activeRequests.length;
for (i = 0; i < activeLength; ++i) {
request = activeRequests[i];
if (request.cancelled) {
// Request was explicitly cancelled
cancelRequest(request);
}
if (request.state !== RequestState$1.ACTIVE) {
// Request is no longer active, remove from array
++removeCount;
continue;
}
if (removeCount > 0) {
// Shift back to fill in vacated slots from completed requests
activeRequests[i - removeCount] = request;
}
}
activeRequests.length -= removeCount;
// Update priority of issued requests and resort the heap
const issuedRequests = requestHeap.internalArray;
const issuedLength = requestHeap.length;
for (i = 0; i < issuedLength; ++i) {
updatePriority(issuedRequests[i]);
}
requestHeap.resort();
// Get the number of open slots and fill with the highest priority requests.
// Un-throttled requests are automatically added to activeRequests, so activeRequests.length may exceed maximumRequests
const openSlots = Math.max(
RequestScheduler.maximumRequests - activeRequests.length,
0
);
let filledSlots = 0;
while (filledSlots < openSlots && requestHeap.length > 0) {
// Loop until all open slots are filled or the heap becomes empty
request = requestHeap.pop();
if (request.cancelled) {
// Request was explicitly cancelled
cancelRequest(request);
continue;
}
if (
request.throttleByServer &&
!RequestScheduler.serverHasOpenSlots(request.serverKey)
) {
// Open slots are available, but the request is throttled by its server. Cancel and try again later.
cancelRequest(request);
continue;
}
startRequest(request);
++filledSlots;
}
updateStatistics();
};
/**
* Get the server key from a given url.
*
* @param {String} url The url.
* @returns {String} The server key.
* @private
*/
RequestScheduler.getServerKey = function (url) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.string("url", url);
//>>includeEnd('debug');
let uri = new URI(url);
if (uri.scheme() === "") {
uri = new URI(url).absoluteTo(pageUri);
uri.normalize();
}
let serverKey = uri.authority();
if (!/:/.test(serverKey)) {
// If the authority does not contain a port number, add port 443 for https or port 80 for http
serverKey = `${serverKey}:${uri.scheme() === "https" ? "443" : "80"}`;
}
const length = numberOfActiveRequestsByServer[serverKey];
if (!when.defined(length)) {
numberOfActiveRequestsByServer[serverKey] = 0;
}
return serverKey;
};
/**
* Issue a request. If request.throttle is false, the request is sent immediately. Otherwise the request will be
* queued and sorted by priority before being sent.
*
* @param {Request} request The request object.
*
* @returns {Promise|undefined} A Promise for the requested data, or undefined if this request does not have high enough priority to be issued.
*
* @private
*/
RequestScheduler.request = function (request) {
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.object("request", request);
RuntimeError.Check.typeOf.string("request.url", request.url);
RuntimeError.Check.typeOf.func("request.requestFunction", request.requestFunction);
//>>includeEnd('debug');
if (isDataUri(request.url) || isBlobUri(request.url)) {
requestCompletedEvent.raiseEvent();
request.state = RequestState$1.RECEIVED;
return request.requestFunction();
}
++statistics.numberOfAttemptedRequests;
if (!when.defined(request.serverKey)) {
request.serverKey = RequestScheduler.getServerKey(request.url);
}
if (
RequestScheduler.throttleRequests &&
request.throttleByServer &&
!RequestScheduler.serverHasOpenSlots(request.serverKey)
) {
// Server is saturated. Try again later.
return undefined;
}
if (!RequestScheduler.throttleRequests || !request.throttle) {
return startRequest(request);
}
if (activeRequests.length >= RequestScheduler.maximumRequests) {
// Active requests are saturated. Try again later.
return undefined;
}
// Insert into the priority heap and see if a request was bumped off. If this request is the lowest
// priority it will be returned.
updatePriority(request);
const removedRequest = requestHeap.insert(request);
if (when.defined(removedRequest)) {
if (removedRequest === request) {
// Request does not have high enough priority to be issued
return undefined;
}
// A previously issued request has been bumped off the priority heap, so cancel it
cancelRequest(removedRequest);
}
return issueRequest(request);
};
function updateStatistics() {
if (!RequestScheduler.debugShowStatistics) {
return;
}
if (
statistics.numberOfActiveRequests === 0 &&
statistics.lastNumberOfActiveRequests > 0
) {
if (statistics.numberOfAttemptedRequests > 0) {
console.log(
`Number of attempted requests: ${statistics.numberOfAttemptedRequests}`
);
statistics.numberOfAttemptedRequests = 0;
}
if (statistics.numberOfCancelledRequests > 0) {
console.log(
`Number of cancelled requests: ${statistics.numberOfCancelledRequests}`
);
statistics.numberOfCancelledRequests = 0;
}
if (statistics.numberOfCancelledActiveRequests > 0) {
console.log(
`Number of cancelled active requests: ${statistics.numberOfCancelledActiveRequests}`
);
statistics.numberOfCancelledActiveRequests = 0;
}
if (statistics.numberOfFailedRequests > 0) {
console.log(
`Number of failed requests: ${statistics.numberOfFailedRequests}`
);
statistics.numberOfFailedRequests = 0;
}
}
statistics.lastNumberOfActiveRequests = statistics.numberOfActiveRequests;
}
/**
* For testing only. Clears any requests that may not have completed from previous tests.
*
* @private
*/
RequestScheduler.clearForSpecs = function () {
while (requestHeap.length > 0) {
const request = requestHeap.pop();
cancelRequest(request);
}
const length = activeRequests.length;
for (let i = 0; i < length; ++i) {
cancelRequest(activeRequests[i]);
}
activeRequests.length = 0;
numberOfActiveRequestsByServer = {};
// Clear stats
statistics.numberOfAttemptedRequests = 0;
statistics.numberOfActiveRequests = 0;
statistics.numberOfCancelledRequests = 0;
statistics.numberOfCancelledActiveRequests = 0;
statistics.numberOfFailedRequests = 0;
statistics.numberOfActiveRequestsEver = 0;
statistics.lastNumberOfActiveRequests = 0;
};
/**
* For testing only.
*
* @private
*/
RequestScheduler.numberOfActiveRequestsByServer = function (serverKey) {
return numberOfActiveRequestsByServer[serverKey];
};
/**
* For testing only.
*
* @private
*/
RequestScheduler.requestHeap = requestHeap;
/**
* A singleton that contains all of the servers that are trusted. Credentials will be sent with
* any requests to these servers.
*
* @namespace TrustedServers
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
*/
const TrustedServers = {};
let _servers = {};
/**
* Adds a trusted server to the registry
*
* @param {String} host The host to be added.
* @param {Number} port The port used to access the host.
*
* @example
* // Add a trusted server
* TrustedServers.add('my.server.com', 80);
*/
TrustedServers.add = function (host, port) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(host)) {
throw new RuntimeError.DeveloperError("host is required.");
}
if (!when.defined(port) || port <= 0) {
throw new RuntimeError.DeveloperError("port is required to be greater than 0.");
}
//>>includeEnd('debug');
const authority = `${host.toLowerCase()}:${port}`;
if (!when.defined(_servers[authority])) {
_servers[authority] = true;
}
};
/**
* Removes a trusted server from the registry
*
* @param {String} host The host to be removed.
* @param {Number} port The port used to access the host.
*
* @example
* // Remove a trusted server
* TrustedServers.remove('my.server.com', 80);
*/
TrustedServers.remove = function (host, port) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(host)) {
throw new RuntimeError.DeveloperError("host is required.");
}
if (!when.defined(port) || port <= 0) {
throw new RuntimeError.DeveloperError("port is required to be greater than 0.");
}
//>>includeEnd('debug');
const authority = `${host.toLowerCase()}:${port}`;
if (when.defined(_servers[authority])) {
delete _servers[authority];
}
};
function getAuthority(url) {
const uri = new URI(url);
uri.normalize();
// Removes username:password@ so we just have host[:port]
let authority = uri.authority();
if (authority.length === 0) {
return undefined; // Relative URL
}
uri.authority(authority);
if (authority.indexOf("@") !== -1) {
const parts = authority.split("@");
authority = parts[1];
}
// If the port is missing add one based on the scheme
if (authority.indexOf(":") === -1) {
let scheme = uri.scheme();
if (scheme.length === 0) {
scheme = window.location.protocol;
scheme = scheme.substring(0, scheme.length - 1);
}
if (scheme === "http") {
authority += ":80";
} else if (scheme === "https") {
authority += ":443";
} else {
return undefined;
}
}
return authority;
}
/**
* Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
*
* @param {String} url The url to be tested against the trusted list
*
* @returns {boolean} Returns true if url is trusted, false otherwise.
*
* @example
* // Add server
* TrustedServers.add('my.server.com', 81);
*
* // Check if server is trusted
* if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
* // my.server.com:81 is trusted
* }
* if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
* // my.server.com isn't trusted
* }
*/
TrustedServers.contains = function (url) {
//>>includeStart('debug', pragmas.debug);
if (!when.defined(url)) {
throw new RuntimeError.DeveloperError("url is required.");
}
//>>includeEnd('debug');
const authority = getAuthority(url);
if (when.defined(authority) && when.defined(_servers[authority])) {
return true;
}
return false;
};
/**
* Clears the registry
*
* @example
* // Remove a trusted server
* TrustedServers.clear();
*/
TrustedServers.clear = function () {
_servers = {};
};
const xhrBlobSupported = (function () {
try {
const xhr = new XMLHttpRequest();
xhr.open("GET", "#", true);
xhr.responseType = "blob";
return xhr.responseType === "blob";
} catch (e) {
return false;
}
})();
/**
* Parses a query string and returns the object equivalent.
*
* @param {Uri} uri The Uri with a query object.
* @param {Resource} resource The Resource that will be assigned queryParameters.
* @param {Boolean} merge If true, we'll merge with the resource's existing queryParameters. Otherwise they will be replaced.
* @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in uri will take precedence.
*
* @private
*/
function parseQuery(uri, resource, merge, preserveQueryParameters) {
const queryString = uri.query();
if (queryString.length === 0) {
return {};
}
let query;
// Special case we run into where the querystring is just a string, not key/value pairs
if (queryString.indexOf("=") === -1) {
const result = {};
result[queryString] = undefined;
query = result;
} else {
query = queryToObject(queryString);
}
if (merge) {
resource._queryParameters = combineQueryParameters(
query,
resource._queryParameters,
preserveQueryParameters
);
} else {
resource._queryParameters = query;
}
uri.search("");
}
/**
* Converts a query object into a string.
*
* @param {Uri} uri The Uri object that will have the query object set.
* @param {Resource} resource The resource that has queryParameters
*
* @private
*/
function stringifyQuery(uri, resource) {
const queryObject = resource._queryParameters;
const keys = Object.keys(queryObject);
// We have 1 key with an undefined value, so this is just a string, not key/value pairs
if (keys.length === 1 && !when.defined(queryObject[keys[0]])) {
uri.search(keys[0]);
} else {
uri.search(objectToQuery(queryObject));
}
}
/**
* Clones a value if it is defined, otherwise returns the default value
*
* @param {*} [val] The value to clone.
* @param {*} [defaultVal] The default value.
*
* @returns {*} A clone of val or the defaultVal.
*
* @private
*/
function defaultClone(val, defaultVal) {
if (!when.defined(val)) {
return defaultVal;
}
return when.defined(val.clone) ? val.clone() : clone(val);
}
/**
* Checks to make sure the Resource isn't already being requested.
*
* @param {Request} request The request to check.
*
* @private
*/
function checkAndResetRequest(request) {
if (
request.state === RequestState$1.ISSUED ||
request.state === RequestState$1.ACTIVE
) {
throw new RuntimeError.RuntimeError("The Resource is already being fetched.");
}
request.state = RequestState$1.UNISSUED;
request.deferred = undefined;
}
/**
* This combines a map of query parameters.
*
* @param {Object} q1 The first map of query parameters. Values in this map will take precedence if preserveQueryParameters is false.
* @param {Object} q2 The second map of query parameters.
* @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in q1 will take precedence.
*
* @returns {Object} The combined map of query parameters.
*
* @example
* const q1 = {
* a: 1,
* b: 2
* };
* const q2 = {
* a: 3,
* c: 4
* };
* const q3 = {
* b: [5, 6],
* d: 7
* }
*
* // Returns
* // {
* // a: [1, 3],
* // b: 2,
* // c: 4
* // };
* combineQueryParameters(q1, q2, true);
*
* // Returns
* // {
* // a: 1,
* // b: 2,
* // c: 4
* // };
* combineQueryParameters(q1, q2, false);
*
* // Returns
* // {
* // a: 1,
* // b: [2, 5, 6],
* // d: 7
* // };
* combineQueryParameters(q1, q3, true);
*
* // Returns
* // {
* // a: 1,
* // b: 2,
* // d: 7
* // };
* combineQueryParameters(q1, q3, false);
*
* @private
*/
function combineQueryParameters(q1, q2, preserveQueryParameters) {
if (!preserveQueryParameters) {
return combine.combine(q1, q2);
}
const result = clone(q1, true);
for (const param in q2) {
if (q2.hasOwnProperty(param)) {
let value = result[param];
const q2Value = q2[param];
if (when.defined(value)) {
if (!Array.isArray(value)) {
value = result[param] = [value];
}
result[param] = value.concat(q2Value);
} else {
result[param] = Array.isArray(q2Value) ? q2Value.slice() : q2Value;
}
}
}
return result;
}
/**
* A resource that includes the location and any other parameters we need to retrieve it or create derived resources. It also provides the ability to retry requests.
*
* @alias Resource
* @constructor
*
* @param {String|Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
*
* @example
* function refreshTokenRetryCallback(resource, error) {
* if (error.statusCode === 403) {
* // 403 status code means a new token should be generated
* return getNewAccessToken()
* .then(function(token) {
* resource.queryParameters.access_token = token;
* return true;
* })
* .otherwise(function() {
* return false;
* });
* }
*
* return false;
* }
*
* const resource = new Resource({
* url: 'http://server.com/path/to/resource.json',
* proxy: new DefaultProxy('/proxy/'),
* headers: {
* 'X-My-Header': 'valueOfHeader'
* },
* queryParameters: {
* 'access_token': '123-435-456-000'
* },
* retryCallback: refreshTokenRetryCallback,
* retryAttempts: 1
* });
*/
function Resource(options) {
options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
if (typeof options === "string") {
options = {
url: options,
};
}
//>>includeStart('debug', pragmas.debug);
RuntimeError.Check.typeOf.string("options.url", options.url);
//>>includeEnd('debug');
this._url = undefined;
this._templateValues = defaultClone(options.templateValues, {});
this._queryParameters = defaultClone(options.queryParameters, {});
/**
* Additional HTTP headers that will be sent with the request.
*
* @type {Object}
*/
this.headers = defaultClone(options.headers, {});
/**
* A Request object that will be used. Intended for internal use only.
*
* @type {Request}
*/
this.request = when.defaultValue(options.request, new Request());
/**
* A proxy to be used when loading the resource.
*
* @type {Proxy}
*/
this.proxy = options.proxy;
/**
* Function to call when a request for this resource fails. If it returns true or a Promise that resolves to true, the request will be retried.
*
* @type {Function}
*/
this.retryCallback = options.retryCallback;
/**
* The number of times the retryCallback should be called before giving up.
*
* @type {Number}
*/
this.retryAttempts = when.defaultValue(options.retryAttempts, 0);
this._retryCount = 0;
const uri = new URI(options.url);
parseQuery(uri, this, true, true);
// Remove the fragment as it's not sent with a request
uri.fragment("");
this._url = uri.toString();
}
/**
* A helper function to create a resource depending on whether we have a String or a Resource
*
* @param {Resource|String} resource A Resource or a String to use when creating a new Resource.
*
* @returns {Resource} If resource is a String, a Resource constructed with the url and options. Otherwise the resource parameter is returned.
*
* @private
*/
Resource.createIfNeeded = function (resource) {
if (resource instanceof Resource) {
// Keep existing request object. This function is used internally to duplicate a Resource, so that it can't
// be modified outside of a class that holds it (eg. an imagery or terrain provider). Since the Request objects
// are managed outside of the providers, by the tile loading code, we want to keep the request property the same so if it is changed
// in the underlying tiling code the requests for this resource will use it.
return resource.getDerivedResource({
request: resource.request,
});
}
if (typeof resource !== "string") {
return resource;
}
return new Resource({
url: resource,
});
};
let supportsImageBitmapOptionsPromise;
/**
* A helper function to check whether createImageBitmap supports passing ImageBitmapOptions.
*
* @returns {Promiserequest.throttle
is true and the request does not have high enough priority.
*
* @example
* // load a single URL asynchronously
* resource.fetchArrayBuffer().then(function(arrayBuffer) {
* // use the data
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.fetchArrayBuffer = function () {
return this.fetch({
responseType: "arraybuffer",
});
};
/**
* Creates a Resource and calls fetchArrayBuffer() on it.
*
* @param {String|Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @returns {Promise.request.throttle
is true and the request does not have high enough priority.
*/
Resource.fetchArrayBuffer = function (options) {
const resource = new Resource(options);
return resource.fetchArrayBuffer();
};
/**
* Asynchronously loads the given resource as a blob. Returns a promise that will resolve to
* a Blob once loaded, or reject if the resource failed to load. The data is loaded
* using XMLHttpRequest, which means that in order to make requests to another origin,
* the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
*
* @returns {Promise.request.throttle
is true and the request does not have high enough priority.
*
* @example
* // load a single URL asynchronously
* resource.fetchBlob().then(function(blob) {
* // use the data
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.fetchBlob = function () {
return this.fetch({
responseType: "blob",
});
};
/**
* Creates a Resource and calls fetchBlob() on it.
*
* @param {String|Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @returns {Promise.request.throttle
is true and the request does not have high enough priority.
*/
Resource.fetchBlob = function (options) {
const resource = new Resource(options);
return resource.fetchBlob();
};
/**
* Asynchronously loads the given image resource. Returns a promise that will resolve to
* an {@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap|ImageBitmap} if preferImageBitmap
is true and the browser supports createImageBitmap
or otherwise an
* {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement|Image} once loaded, or reject if the image failed to load.
*
* @param {Object} [options] An object with the following properties.
* @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
* @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an ImageBitmap
is returned.
* @param {Boolean} [options.flipY=false] If true, image will be vertically flipped during decode. Only applies if the browser supports createImageBitmap
.
* @param {Boolean} [options.skipColorSpaceConversion=false] If true, any custom gamma or color profiles in the image will be ignored. Only applies if the browser supports createImageBitmap
.
* @returns {Promise.request.throttle
is true and the request does not have high enough priority.
*
*
* @example
* // load a single image asynchronously
* resource.fetchImage().then(function(image) {
* // use the loaded image
* }).otherwise(function(error) {
* // an error occurred
* });
*
* // load several images in parallel
* when.all([resource1.fetchImage(), resource2.fetchImage()]).then(function(images) {
* // images is an array containing all the loaded images
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.fetchImage = function (options) {
options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
const preferImageBitmap = when.defaultValue(options.preferImageBitmap, false);
const preferBlob = when.defaultValue(options.preferBlob, false);
const flipY = when.defaultValue(options.flipY, false);
const skipColorSpaceConversion = when.defaultValue(
options.skipColorSpaceConversion,
false
);
checkAndResetRequest(this.request);
// We try to load the image normally if
// 1. Blobs aren't supported
// 2. It's a data URI
// 3. It's a blob URI
// 4. It doesn't have request headers and we preferBlob is false
if (
!xhrBlobSupported ||
this.isDataUri ||
this.isBlobUri ||
(!this.hasHeaders && !preferBlob)
) {
return fetchImage({
resource: this,
flipY: flipY,
skipColorSpaceConversion: skipColorSpaceConversion,
preferImageBitmap: preferImageBitmap,
});
}
const blobPromise = this.fetchBlob();
if (!when.defined(blobPromise)) {
return;
}
let supportsImageBitmap;
let useImageBitmap;
let generatedBlobResource;
let generatedBlob;
return Resource.supportsImageBitmapOptions()
.then(function (result) {
supportsImageBitmap = result;
useImageBitmap = supportsImageBitmap && preferImageBitmap;
return blobPromise;
})
.then(function (blob) {
if (!when.defined(blob)) {
return;
}
generatedBlob = blob;
if (useImageBitmap) {
return Resource.createImageBitmapFromBlob(blob, {
flipY: flipY,
premultiplyAlpha: false,
skipColorSpaceConversion: skipColorSpaceConversion,
});
}
const blobUrl = window.URL.createObjectURL(blob);
generatedBlobResource = new Resource({
url: blobUrl,
});
return fetchImage({
resource: generatedBlobResource,
flipY: flipY,
skipColorSpaceConversion: skipColorSpaceConversion,
preferImageBitmap: false,
});
})
.then(function (image) {
if (!when.defined(image)) {
return;
}
// The blob object may be needed for use by a TileDiscardPolicy,
// so attach it to the image.
image.blob = generatedBlob;
if (useImageBitmap) {
return image;
}
window.URL.revokeObjectURL(generatedBlobResource.url);
return image;
})
.otherwise(function (error) {
if (when.defined(generatedBlobResource)) {
window.URL.revokeObjectURL(generatedBlobResource.url);
}
// If the blob load succeeded but the image decode failed, attach the blob
// to the error object for use by a TileDiscardPolicy.
// In particular, BingMapsImageryProvider uses this to detect the
// zero-length response that is returned when a tile is not available.
error.blob = generatedBlob;
return when.when.reject(error);
});
};
/**
* Fetches an image and returns a promise to it.
*
* @param {Object} [options] An object with the following properties.
* @param {Resource} [options.resource] Resource object that points to an image to fetch.
* @param {Boolean} [options.preferImageBitmap] If true, image will be decoded during fetch and an ImageBitmap
is returned.
* @param {Boolean} [options.flipY] If true, image will be vertically flipped during decode. Only applies if the browser supports createImageBitmap
.
* @param {Boolean} [options.skipColorSpaceConversion=false] If true, any custom gamma or color profiles in the image will be ignored. Only applies if the browser supports createImageBitmap
.
* @private
*/
function fetchImage(options) {
const resource = options.resource;
const flipY = options.flipY;
const skipColorSpaceConversion = options.skipColorSpaceConversion;
const preferImageBitmap = options.preferImageBitmap;
const request = resource.request;
request.url = resource.url;
request.requestFunction = function () {
let crossOrigin = false;
// data URIs can't have crossorigin set.
if (!resource.isDataUri && !resource.isBlobUri) {
crossOrigin = resource.isCrossOriginUrl;
}
const deferred = when.when.defer();
Resource._Implementations.createImage(
request,
crossOrigin,
deferred,
flipY,
skipColorSpaceConversion,
preferImageBitmap
);
return deferred.promise;
};
const promise = RequestScheduler.request(request);
if (!when.defined(promise)) {
return;
}
return promise.otherwise(function (e) {
// Don't retry cancelled or otherwise aborted requests
if (request.state !== RequestState$1.FAILED) {
return when.when.reject(e);
}
return resource.retryOnError(e).then(function (retry) {
if (retry) {
// Reset request so it can try again
request.state = RequestState$1.UNISSUED;
request.deferred = undefined;
return fetchImage({
resource: resource,
flipY: flipY,
skipColorSpaceConversion: skipColorSpaceConversion,
preferImageBitmap: preferImageBitmap,
});
}
return when.when.reject(e);
});
});
}
/**
* Creates a Resource and calls fetchImage() on it.
*
* @param {String|Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Boolean} [options.flipY=false] Whether to vertically flip the image during fetch and decode. Only applies when requesting an image and the browser supports createImageBitmap
.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
* @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an ImageBitmap
is returned.
* @param {Boolean} [options.skipColorSpaceConversion=false] If true, any custom gamma or color profiles in the image will be ignored. Only applies when requesting an image and the browser supports createImageBitmap
.
* @returns {Promise.request.throttle
is true and the request does not have high enough priority.
*/
Resource.fetchImage = function (options) {
const resource = new Resource(options);
return resource.fetchImage({
flipY: options.flipY,
skipColorSpaceConversion: options.skipColorSpaceConversion,
preferBlob: options.preferBlob,
preferImageBitmap: options.preferImageBitmap,
});
};
/**
* Asynchronously loads the given resource as text. Returns a promise that will resolve to
* a String once loaded, or reject if the resource failed to load. The data is loaded
* using XMLHttpRequest, which means that in order to make requests to another origin,
* the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
*
* @returns {Promise.request.throttle
is true and the request does not have high enough priority.
*
* @example
* // load text from a URL, setting a custom header
* const resource = new Resource({
* url: 'http://someUrl.com/someJson.txt',
* headers: {
* 'X-Custom-Header' : 'some value'
* }
* });
* resource.fetchText().then(function(text) {
* // Do something with the text
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.fetchText = function () {
return this.fetch({
responseType: "text",
});
};
/**
* Creates a Resource and calls fetchText() on it.
*
* @param {String|Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @returns {Promise.request.throttle
is true and the request does not have high enough priority.
*/
Resource.fetchText = function (options) {
const resource = new Resource(options);
return resource.fetchText();
};
// note: */* below is */* but that ends the comment block early
/**
* Asynchronously loads the given resource as JSON. Returns a promise that will resolve to
* a JSON object once loaded, or reject if the resource failed to load. The data is loaded
* using XMLHttpRequest, which means that in order to make requests to another origin,
* the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
* adds 'Accept: application/json,*/*;q=0.01' to the request headers, if not
* already specified.
*
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*
*
* @example
* resource.fetchJson().then(function(jsonData) {
* // Do something with the JSON object
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.fetchJson = function () {
const promise = this.fetch({
responseType: "text",
headers: {
Accept: "application/json,*/*;q=0.01",
},
});
if (!when.defined(promise)) {
return undefined;
}
return promise.then(function (value) {
if (!when.defined(value)) {
return;
}
return JSON.parse(value);
});
};
/**
* Creates a Resource and calls fetchJson() on it.
*
* @param {String|Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*/
Resource.fetchJson = function (options) {
const resource = new Resource(options);
return resource.fetchJson();
};
/**
* Asynchronously loads the given resource as XML. Returns a promise that will resolve to
* an XML Document once loaded, or reject if the resource failed to load. The data is loaded
* using XMLHttpRequest, which means that in order to make requests to another origin,
* the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
*
* @returns {Promise.request.throttle
is true and the request does not have high enough priority.
*
*
* @example
* // load XML from a URL, setting a custom header
* Cesium.loadXML('http://someUrl.com/someXML.xml', {
* 'X-Custom-Header' : 'some value'
* }).then(function(document) {
* // Do something with the document
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.fetchXML = function () {
return this.fetch({
responseType: "document",
overrideMimeType: "text/xml",
});
};
/**
* Creates a Resource and calls fetchXML() on it.
*
* @param {String|Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @returns {Promise.request.throttle
is true and the request does not have high enough priority.
*/
Resource.fetchXML = function (options) {
const resource = new Resource(options);
return resource.fetchXML();
};
/**
* Requests a resource using JSONP.
*
* @param {String} [callbackParameterName='callback'] The callback parameter name that the server expects.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*
*
* @example
* // load a data asynchronously
* resource.fetchJsonp().then(function(data) {
* // use the loaded data
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.fetchJsonp = function (callbackParameterName) {
callbackParameterName = when.defaultValue(callbackParameterName, "callback");
checkAndResetRequest(this.request);
//generate a unique function name
let functionName;
do {
functionName = `loadJsonp${ComponentDatatype.CesiumMath.nextRandomNumber()
.toString()
.substring(2, 8)}`;
} while (when.defined(window[functionName]));
return fetchJsonp(this, callbackParameterName, functionName);
};
function fetchJsonp(resource, callbackParameterName, functionName) {
const callbackQuery = {};
callbackQuery[callbackParameterName] = functionName;
resource.setQueryParameters(callbackQuery);
const request = resource.request;
request.url = resource.url;
request.requestFunction = function () {
const deferred = when.when.defer();
//assign a function with that name in the global scope
window[functionName] = function (data) {
deferred.resolve(data);
try {
delete window[functionName];
} catch (e) {
window[functionName] = undefined;
}
};
Resource._Implementations.loadAndExecuteScript(
resource.url,
functionName,
deferred
);
return deferred.promise;
};
const promise = RequestScheduler.request(request);
if (!when.defined(promise)) {
return;
}
return promise.otherwise(function (e) {
if (request.state !== RequestState$1.FAILED) {
return when.when.reject(e);
}
return resource.retryOnError(e).then(function (retry) {
if (retry) {
// Reset request so it can try again
request.state = RequestState$1.UNISSUED;
request.deferred = undefined;
return fetchJsonp(resource, callbackParameterName, functionName);
}
return when.when.reject(e);
});
});
}
/**
* Creates a Resource from a URL and calls fetchJsonp() on it.
*
* @param {String|Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @param {String} [options.callbackParameterName='callback'] The callback parameter name that the server expects.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*/
Resource.fetchJsonp = function (options) {
const resource = new Resource(options);
return resource.fetchJsonp(options.callbackParameterName);
};
/**
* @private
*/
Resource.prototype._makeRequest = function (options) {
const resource = this;
checkAndResetRequest(resource.request);
const request = resource.request;
request.url = resource.url;
request.requestFunction = function () {
const responseType = options.responseType;
const headers = combine.combine(options.headers, resource.headers);
const overrideMimeType = options.overrideMimeType;
const method = options.method;
const data = options.data;
const deferred = when.when.defer();
const xhr = Resource._Implementations.loadWithXhr(
resource.url,
responseType,
method,
data,
headers,
deferred,
overrideMimeType
);
if (when.defined(xhr) && when.defined(xhr.abort)) {
request.cancelFunction = function () {
xhr.abort();
};
}
return deferred.promise;
};
const promise = RequestScheduler.request(request);
if (!when.defined(promise)) {
return;
}
return promise
.then(function (data) {
// explicitly set to undefined to ensure GC of request response data. See #8843
request.cancelFunction = undefined;
return data;
})
.otherwise(function (e) {
request.cancelFunction = undefined;
if (request.state !== RequestState$1.FAILED) {
return when.when.reject(e);
}
return resource.retryOnError(e).then(function (retry) {
if (retry) {
// Reset request so it can try again
request.state = RequestState$1.UNISSUED;
request.deferred = undefined;
return resource.fetch(options);
}
return when.when.reject(e);
});
});
};
const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
function decodeDataUriText(isBase64, data) {
const result = decodeURIComponent(data);
if (isBase64) {
return atob(result);
}
return result;
}
function decodeDataUriArrayBuffer(isBase64, data) {
const byteString = decodeDataUriText(isBase64, data);
const buffer = new ArrayBuffer(byteString.length);
const view = new Uint8Array(buffer);
for (let i = 0; i < byteString.length; i++) {
view[i] = byteString.charCodeAt(i);
}
return buffer;
}
function decodeDataUri(dataUriRegexResult, responseType) {
responseType = when.defaultValue(responseType, "");
const mimeType = dataUriRegexResult[1];
const isBase64 = !!dataUriRegexResult[2];
const data = dataUriRegexResult[3];
let buffer;
let parser;
switch (responseType) {
case "":
case "text":
return decodeDataUriText(isBase64, data);
case "arraybuffer":
return decodeDataUriArrayBuffer(isBase64, data);
case "blob":
buffer = decodeDataUriArrayBuffer(isBase64, data);
return new Blob([buffer], {
type: mimeType,
});
case "document":
parser = new DOMParser();
return parser.parseFromString(
decodeDataUriText(isBase64, data),
mimeType
);
case "json":
return JSON.parse(decodeDataUriText(isBase64, data));
default:
//>>includeStart('debug', pragmas.debug);
throw new RuntimeError.DeveloperError(`Unhandled responseType: ${responseType}`);
//>>includeEnd('debug');
}
}
/**
* Asynchronously loads the given resource. Returns a promise that will resolve to
* the result once loaded, or reject if the resource failed to load. The data is loaded
* using XMLHttpRequest, which means that in order to make requests to another origin,
* the server must have Cross-Origin Resource Sharing (CORS) headers enabled. It's recommended that you use
* the more specific functions eg. fetchJson, fetchBlob, etc.
*
* @param {Object} [options] Object with the following properties:
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*
*
* @example
* resource.fetch()
* .then(function(body) {
* // use the data
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.fetch = function (options) {
options = defaultClone(options, {});
options.method = "GET";
return this._makeRequest(options);
};
/**
* Creates a Resource from a URL and calls fetch() on it.
*
* @param {String|Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*/
Resource.fetch = function (options) {
const resource = new Resource(options);
return resource.fetch({
// Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
responseType: options.responseType,
overrideMimeType: options.overrideMimeType,
});
};
/**
* Asynchronously deletes the given resource. Returns a promise that will resolve to
* the result once loaded, or reject if the resource failed to load. The data is loaded
* using XMLHttpRequest, which means that in order to make requests to another origin,
* the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
*
* @param {Object} [options] Object with the following properties:
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*
*
* @example
* resource.delete()
* .then(function(body) {
* // use the data
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.delete = function (options) {
options = defaultClone(options, {});
options.method = "DELETE";
return this._makeRequest(options);
};
/**
* Creates a Resource from a URL and calls delete() on it.
*
* @param {String|Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} [options.data] Data that is posted with the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*/
Resource.delete = function (options) {
const resource = new Resource(options);
return resource.delete({
// Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
responseType: options.responseType,
overrideMimeType: options.overrideMimeType,
data: options.data,
});
};
/**
* Asynchronously gets headers the given resource. Returns a promise that will resolve to
* the result once loaded, or reject if the resource failed to load. The data is loaded
* using XMLHttpRequest, which means that in order to make requests to another origin,
* the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
*
* @param {Object} [options] Object with the following properties:
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*
*
* @example
* resource.head()
* .then(function(headers) {
* // use the data
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.head = function (options) {
options = defaultClone(options, {});
options.method = "HEAD";
return this._makeRequest(options);
};
/**
* Creates a Resource from a URL and calls head() on it.
*
* @param {String|Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*/
Resource.head = function (options) {
const resource = new Resource(options);
return resource.head({
// Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
responseType: options.responseType,
overrideMimeType: options.overrideMimeType,
});
};
/**
* Asynchronously gets options the given resource. Returns a promise that will resolve to
* the result once loaded, or reject if the resource failed to load. The data is loaded
* using XMLHttpRequest, which means that in order to make requests to another origin,
* the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
*
* @param {Object} [options] Object with the following properties:
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*
*
* @example
* resource.options()
* .then(function(headers) {
* // use the data
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.options = function (options) {
options = defaultClone(options, {});
options.method = "OPTIONS";
return this._makeRequest(options);
};
/**
* Creates a Resource from a URL and calls options() on it.
*
* @param {String|Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*/
Resource.options = function (options) {
const resource = new Resource(options);
return resource.options({
// Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
responseType: options.responseType,
overrideMimeType: options.overrideMimeType,
});
};
/**
* Asynchronously posts data to the given resource. Returns a promise that will resolve to
* the result once loaded, or reject if the resource failed to load. The data is loaded
* using XMLHttpRequest, which means that in order to make requests to another origin,
* the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
*
* @param {Object} data Data that is posted with the resource.
* @param {Object} [options] Object with the following properties:
* @param {Object} [options.data] Data that is posted with the resource.
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*
*
* @example
* resource.post(data)
* .then(function(result) {
* // use the result
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.post = function (data, options) {
RuntimeError.Check.defined("data", data);
options = defaultClone(options, {});
options.method = "POST";
options.data = data;
return this._makeRequest(options);
};
/**
* Creates a Resource from a URL and calls post() on it.
*
* @param {Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} options.data Data that is posted with the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*/
Resource.post = function (options) {
const resource = new Resource(options);
return resource.post(options.data, {
// Make copy of just the needed fields because headers can be passed to both the constructor and to post
responseType: options.responseType,
overrideMimeType: options.overrideMimeType,
});
};
/**
* Asynchronously puts data to the given resource. Returns a promise that will resolve to
* the result once loaded, or reject if the resource failed to load. The data is loaded
* using XMLHttpRequest, which means that in order to make requests to another origin,
* the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
*
* @param {Object} data Data that is posted with the resource.
* @param {Object} [options] Object with the following properties:
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*
*
* @example
* resource.put(data)
* .then(function(result) {
* // use the result
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.put = function (data, options) {
RuntimeError.Check.defined("data", data);
options = defaultClone(options, {});
options.method = "PUT";
options.data = data;
return this._makeRequest(options);
};
/**
* Creates a Resource from a URL and calls put() on it.
*
* @param {Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} options.data Data that is posted with the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*/
Resource.put = function (options) {
const resource = new Resource(options);
return resource.put(options.data, {
// Make copy of just the needed fields because headers can be passed to both the constructor and to post
responseType: options.responseType,
overrideMimeType: options.overrideMimeType,
});
};
/**
* Asynchronously patches data to the given resource. Returns a promise that will resolve to
* the result once loaded, or reject if the resource failed to load. The data is loaded
* using XMLHttpRequest, which means that in order to make requests to another origin,
* the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
*
* @param {Object} data Data that is posted with the resource.
* @param {Object} [options] Object with the following properties:
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*
*
* @example
* resource.patch(data)
* .then(function(result) {
* // use the result
* }).otherwise(function(error) {
* // an error occurred
* });
*
* @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
* @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
*/
Resource.prototype.patch = function (data, options) {
RuntimeError.Check.defined("data", data);
options = defaultClone(options, {});
options.method = "PATCH";
options.data = data;
return this._makeRequest(options);
};
/**
* Creates a Resource from a URL and calls patch() on it.
*
* @param {Object} options A url or an object with the following properties
* @param {String} options.url The url of the resource.
* @param {Object} options.data Data that is posted with the resource.
* @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
* @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
* @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
* @param {Proxy} [options.proxy] A proxy to be used when loading the resource.
* @param {Resource.RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
* @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
* @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
* @param {String} [options.responseType] The type of response. This controls the type of item returned.
* @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
* @returns {Promise.<*>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if request.throttle
is true and the request does not have high enough priority.
*/
Resource.patch = function (options) {
const resource = new Resource(options);
return resource.patch(options.data, {
// Make copy of just the needed fields because headers can be passed to both the constructor and to post
responseType: options.responseType,
overrideMimeType: options.overrideMimeType,
});
};
/**
* Contains implementations of functions that can be replaced for testing
*
* @private
*/
Resource._Implementations = {};
function loadImageElement(url, crossOrigin, deferred) {
const image = new Image();
image.onload = function () {
deferred.resolve(image);
};
image.onerror = function (e) {
deferred.reject(e);
};
if (crossOrigin) {
if (TrustedServers.contains(url)) {
image.crossOrigin = "use-credentials";
} else {
image.crossOrigin = "";
}
}
image.src = url;
}
Resource._Implementations.createImage = function (
request,
crossOrigin,
deferred,
flipY,
skipColorSpaceConversion,
preferImageBitmap
) {
const url = request.url;
// Passing an Image to createImageBitmap will force it to run on the main thread
// since DOM elements don't exist on workers. We convert it to a blob so it's non-blocking.
// See:
// https://bugzilla.mozilla.org/show_bug.cgi?id=1044102#c38
// https://bugs.chromium.org/p/chromium/issues/detail?id=580202#c10
Resource.supportsImageBitmapOptions()
.then(function (supportsImageBitmap) {
// We can only use ImageBitmap if we can flip on decode.
// See: https://github.com/CesiumGS/cesium/pull/7579#issuecomment-466146898
if (!(supportsImageBitmap && preferImageBitmap)) {
loadImageElement(url, crossOrigin, deferred);
return;
}
const responseType = "blob";
const method = "GET";
const xhrDeferred = when.when.defer();
const xhr = Resource._Implementations.loadWithXhr(
url,
responseType,
method,
undefined,
undefined,
xhrDeferred,
undefined,
undefined,
undefined
);
if (when.defined(xhr) && when.defined(xhr.abort)) {
request.cancelFunction = function () {
xhr.abort();
};
}
return xhrDeferred.promise
.then(function (blob) {
if (!when.defined(blob)) {
deferred.reject(
new RuntimeError.RuntimeError(
`Successfully retrieved ${url} but it contained no content.`
)
);
return;
}
return Resource.createImageBitmapFromBlob(blob, {
flipY: flipY,
premultiplyAlpha: false,
skipColorSpaceConversion: skipColorSpaceConversion,
});
})
.then(deferred.resolve);
})
.otherwise(deferred.reject);
};
/**
* Wrapper for createImageBitmap
*
* @private
*/
Resource.createImageBitmapFromBlob = function (blob, options) {
RuntimeError.Check.defined("options", options);
RuntimeError.Check.typeOf.bool("options.flipY", options.flipY);
RuntimeError.Check.typeOf.bool("options.premultiplyAlpha", options.premultiplyAlpha);
RuntimeError.Check.typeOf.bool(
"options.skipColorSpaceConversion",
options.skipColorSpaceConversion
);
return createImageBitmap(blob, {
imageOrientation: options.flipY ? "flipY" : "none",
premultiplyAlpha: options.premultiplyAlpha ? "premultiply" : "none",
colorSpaceConversion: options.skipColorSpaceConversion ? "none" : "default",
});
};
function decodeResponse(loadWithHttpResponse, responseType) {
switch (responseType) {
case "text":
return loadWithHttpResponse.toString("utf8");
case "json":
return JSON.parse(loadWithHttpResponse.toString("utf8"));
default:
return new Uint8Array(loadWithHttpResponse).buffer;
}
}
function loadWithHttpRequest(
url,
responseType,
method,
data,
headers,
deferred,
overrideMimeType
) {
// Note: only the 'json' and 'text' responseTypes transforms the loaded buffer
/* eslint-disable no-undef */
const URL = require("url").parse(url);
const http = URL.protocol === "https:" ? require("https") : require("http");
const zlib = require("zlib");
/* eslint-enable no-undef */
const options = {
protocol: URL.protocol,
hostname: URL.hostname,
port: URL.port,
path: URL.path,
query: URL.query,
method: method,
headers: headers,
};
http
.request(options)
.on("response", function (res) {
if (res.statusCode < 200 || res.statusCode >= 300) {
deferred.reject(
new RequestErrorEvent(res.statusCode, res, res.headers)
);
return;
}
const chunkArray = [];
res.on("data", function (chunk) {
chunkArray.push(chunk);
});
res.on("end", function () {
// eslint-disable-next-line no-undef
const result = Buffer.concat(chunkArray);
if (res.headers["content-encoding"] === "gzip") {
zlib.gunzip(result, function (error, resultUnzipped) {
if (error) {
deferred.reject(
new RuntimeError.RuntimeError("Error decompressing response.")
);
} else {
deferred.resolve(decodeResponse(resultUnzipped, responseType));
}
});
} else {
deferred.resolve(decodeResponse(result, responseType));
}
});
})
.on("error", function (e) {
deferred.reject(new RequestErrorEvent());
})
.end();
}
const noXMLHttpRequest = typeof XMLHttpRequest === "undefined";
Resource._Implementations.loadWithXhr = function (
url,
responseType,
method,
data,
headers,
deferred,
overrideMimeType
) {
const dataUriRegexResult = dataUriRegex.exec(url);
if (dataUriRegexResult !== null) {
deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
return;
}
if (noXMLHttpRequest) {
loadWithHttpRequest(
url,
responseType,
method,
data,
headers,
deferred);
return;
}
const xhr = new XMLHttpRequest();
if (TrustedServers.contains(url)) {
xhr.withCredentials = true;
}
xhr.open(method, url, true);
if (when.defined(overrideMimeType) && when.defined(xhr.overrideMimeType)) {
xhr.overrideMimeType(overrideMimeType);
}
if (when.defined(headers)) {
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
xhr.setRequestHeader(key, headers[key]);
}
}
}
if (when.defined(responseType)) {
xhr.responseType = responseType;
}
// While non-standard, file protocol always returns a status of 0 on success
let localFile = false;
if (typeof url === "string") {
localFile =
url.indexOf("file://") === 0 ||
(typeof window !== "undefined" && window.location.origin === "file://");
}
xhr.onload = function () {
if (
(xhr.status < 200 || xhr.status >= 300) &&
!(localFile && xhr.status === 0)
) {
deferred.reject(
new RequestErrorEvent(
xhr.status,
xhr.response,
xhr.getAllResponseHeaders()
)
);
return;
}
const response = xhr.response;
const browserResponseType = xhr.responseType;
if (method === "HEAD" || method === "OPTIONS") {
const responseHeaderString = xhr.getAllResponseHeaders();
const splitHeaders = responseHeaderString.trim().split(/[\r\n]+/);
const responseHeaders = {};
splitHeaders.forEach(function (line) {
const parts = line.split(": ");
const header = parts.shift();
responseHeaders[header] = parts.join(": ");
});
deferred.resolve(responseHeaders);
return;
}
//All modern browsers will go into either the first or second if block or last else block.
//Other code paths support older browsers that either do not support the supplied responseType
//or do not support the xhr.response property.
if (xhr.status === 204) {
// accept no content
deferred.resolve();
} else if (
when.defined(response) &&
(!when.defined(responseType) || browserResponseType === responseType)
) {
deferred.resolve(response);
} else if (responseType === "json" && typeof response === "string") {
try {
deferred.resolve(JSON.parse(response));
} catch (e) {
deferred.reject(e);
}
} else if (
(browserResponseType === "" || browserResponseType === "document") &&
when.defined(xhr.responseXML) &&
xhr.responseXML.hasChildNodes()
) {
deferred.resolve(xhr.responseXML);
} else if (
(browserResponseType === "" || browserResponseType === "text") &&
when.defined(xhr.responseText)
) {
deferred.resolve(xhr.responseText);
} else {
deferred.reject(
new RuntimeError.RuntimeError("Invalid XMLHttpRequest response type.")
);
}
};
xhr.onerror = function (e) {
deferred.reject(new RequestErrorEvent());
};
xhr.send(data);
return xhr;
};
Resource._Implementations.loadAndExecuteScript = function (
url,
functionName,
deferred
) {
return loadAndExecuteScript(url).otherwise(deferred.reject);
};
/**
* The default implementations
*
* @private
*/
Resource._DefaultImplementations = {};
Resource._DefaultImplementations.createImage =
Resource._Implementations.createImage;
Resource._DefaultImplementations.loadWithXhr =
Resource._Implementations.loadWithXhr;
Resource._DefaultImplementations.loadAndExecuteScript =
Resource._Implementations.loadAndExecuteScript;
/**
* A resource instance initialized to the current browser location
*
* @type {Resource}
* @constant
*/
Resource.DEFAULT = Object.freeze(
new Resource({
url:
typeof document === "undefined"
? ""
: document.location.href.split("?")[0],
})
);
/**
* Specifies Earth polar motion coordinates and the difference between UT1 and UTC.
* These Earth Orientation Parameters (EOP) are primarily used in the transformation from
* the International Celestial Reference Frame (ICRF) to the International Terrestrial
* Reference Frame (ITRF).
*
* @alias EarthOrientationParameters
* @constructor
*
* @param {Object} [options] Object with the following properties:
* @param {Resource|String} [options.url] The URL from which to obtain EOP data. If neither this
* parameter nor options.data is specified, all EOP values are assumed
* to be 0.0. If options.data is specified, this parameter is
* ignored.
* @param {Object} [options.data] The actual EOP data. If neither this
* parameter nor options.data is specified, all EOP values are assumed
* to be 0.0.
* @param {Boolean} [options.addNewLeapSeconds=true] True if leap seconds that
* are specified in the EOP data but not in {@link JulianDate.leapSeconds}
* should be added to {@link JulianDate.leapSeconds}. False if
* new leap seconds should be handled correctly in the context
* of the EOP data but otherwise ignored.
*
* @example
* // An example EOP data file, EOP.json:
* {
* "columnNames" : ["dateIso8601","modifiedJulianDateUtc","xPoleWanderRadians","yPoleWanderRadians","ut1MinusUtcSeconds","lengthOfDayCorrectionSeconds","xCelestialPoleOffsetRadians","yCelestialPoleOffsetRadians","taiMinusUtcSeconds"],
* "samples" : [
* "2011-07-01T00:00:00Z",55743.0,2.117957047295119e-7,2.111518721609984e-6,-0.2908948,-2.956e-4,3.393695767766752e-11,3.3452143996557983e-10,34.0,
* "2011-07-02T00:00:00Z",55744.0,2.193297093339541e-7,2.115460256837405e-6,-0.29065,-1.824e-4,-8.241832578862112e-11,5.623838700870617e-10,34.0,
* "2011-07-03T00:00:00Z",55745.0,2.262286080161428e-7,2.1191157519929706e-6,-0.2905572,1.9e-6,-3.490658503988659e-10,6.981317007977318e-10,34.0
* ]
* }
*
* @example
* // Loading the EOP data
* const eop = new Cesium.EarthOrientationParameters({ url : 'Data/EOP.json' });
* Cesium.Transforms.earthOrientationParameters = eop;
*
* @private
*/
function EarthOrientationParameters(options) {
options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
this._dates = undefined;
this._samples = undefined;
this._dateColumn = -1;
this._xPoleWanderRadiansColumn = -1;
this._yPoleWanderRadiansColumn = -1;
this._ut1MinusUtcSecondsColumn = -1;
this._xCelestialPoleOffsetRadiansColumn = -1;
this._yCelestialPoleOffsetRadiansColumn = -1;
this._taiMinusUtcSecondsColumn = -1;
this._columnCount = 0;
this._lastIndex = -1;
this._downloadPromise = undefined;
this._dataError = undefined;
this._addNewLeapSeconds = when.defaultValue(options.addNewLeapSeconds, true);
if (when.defined(options.data)) {
// Use supplied EOP data.
onDataReady(this, options.data);
} else if (when.defined(options.url)) {
const resource = Resource.createIfNeeded(options.url);
// Download EOP data.
const that = this;
this._downloadPromise = resource
.fetchJson()
.then(function (eopData) {
onDataReady(that, eopData);
})
.otherwise(function () {
that._dataError = `An error occurred while retrieving the EOP data from the URL ${resource.url}.`;
});
} else {
// Use all zeros for EOP data.
onDataReady(this, {
columnNames: [
"dateIso8601",
"modifiedJulianDateUtc",
"xPoleWanderRadians",
"yPoleWanderRadians",
"ut1MinusUtcSeconds",
"lengthOfDayCorrectionSeconds",
"xCelestialPoleOffsetRadians",
"yCelestialPoleOffsetRadians",
"taiMinusUtcSeconds",
],
samples: [],
});
}
}
/**
* A default {@link EarthOrientationParameters} instance that returns zero for all EOP values.
*/
EarthOrientationParameters.NONE = Object.freeze({
getPromiseToLoad: function () {
return when.when.resolve();
},
compute: function (date, result) {
if (!when.defined(result)) {
result = new EarthOrientationParametersSample(0.0, 0.0, 0.0, 0.0, 0.0);
} else {
result.xPoleWander = 0.0;
result.yPoleWander = 0.0;
result.xPoleOffset = 0.0;
result.yPoleOffset = 0.0;
result.ut1MinusUtc = 0.0;
}
return result;
},
});
/**
* Gets a promise that, when resolved, indicates that the EOP data has been loaded and is
* ready to use.
*
* @returns {Promisetrue
if they are equal, false
otherwise.
*
* @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
* @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
* @returns {Boolean} true
if left and right are equal, false
otherwise.
*/
HeadingPitchRoll.equals = function (left, right) {
return (
left === right ||
(when.defined(left) &&
when.defined(right) &&
left.heading === right.heading &&
left.pitch === right.pitch &&
left.roll === right.roll)
);
};
/**
* Compares the provided HeadingPitchRolls componentwise and returns
* true
if they pass an absolute or relative tolerance test,
* false
otherwise.
*
* @param {HeadingPitchRoll} [left] The first HeadingPitchRoll.
* @param {HeadingPitchRoll} [right] The second HeadingPitchRoll.
* @param {Number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} true
if left and right are within the provided epsilon, false
otherwise.
*/
HeadingPitchRoll.equalsEpsilon = function (
left,
right,
relativeEpsilon,
absoluteEpsilon
) {
return (
left === right ||
(when.defined(left) &&
when.defined(right) &&
ComponentDatatype.CesiumMath.equalsEpsilon(
left.heading,
right.heading,
relativeEpsilon,
absoluteEpsilon
) &&
ComponentDatatype.CesiumMath.equalsEpsilon(
left.pitch,
right.pitch,
relativeEpsilon,
absoluteEpsilon
) &&
ComponentDatatype.CesiumMath.equalsEpsilon(
left.roll,
right.roll,
relativeEpsilon,
absoluteEpsilon
))
);
};
/**
* Duplicates this HeadingPitchRoll instance.
*
* @param {HeadingPitchRoll} [result] The object onto which to store the result.
* @returns {HeadingPitchRoll} The modified result parameter or a new HeadingPitchRoll instance if one was not provided.
*/
HeadingPitchRoll.prototype.clone = function (result) {
return HeadingPitchRoll.clone(this, result);
};
/**
* Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
* true
if they are equal, false
otherwise.
*
* @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
* @returns {Boolean} true
if they are equal, false
otherwise.
*/
HeadingPitchRoll.prototype.equals = function (right) {
return HeadingPitchRoll.equals(this, right);
};
/**
* Compares this HeadingPitchRoll against the provided HeadingPitchRoll componentwise and returns
* true
if they pass an absolute or relative tolerance test,
* false
otherwise.
*
* @param {HeadingPitchRoll} [right] The right hand side HeadingPitchRoll.
* @param {Number} [relativeEpsilon=0] The relative epsilon tolerance to use for equality testing.
* @param {Number} [absoluteEpsilon=relativeEpsilon] The absolute epsilon tolerance to use for equality testing.
* @returns {Boolean} true
if they are within the provided epsilon, false
otherwise.
*/
HeadingPitchRoll.prototype.equalsEpsilon = function (
right,
relativeEpsilon,
absoluteEpsilon
) {
return HeadingPitchRoll.equalsEpsilon(
this,
right,
relativeEpsilon,
absoluteEpsilon
);
};
/**
* Creates a string representing this HeadingPitchRoll in the format '(heading, pitch, roll)' in radians.
*
* @returns {String} A string representing the provided HeadingPitchRoll in the format '(heading, pitch, roll)'.
*/
HeadingPitchRoll.prototype.toString = function () {
return `(${this.heading}, ${this.pitch}, ${this.roll})`;
};
/*global CESIUM_BASE_URL,define,require*/
const cesiumScriptRegex = /((?:.*\/)|^)Cesium\.js(?:\?|\#|$)/;
function getBaseUrlFromCesiumScript() {
const scripts = document.getElementsByTagName("script");
for (let i = 0, len = scripts.length; i < len; ++i) {
const src = scripts[i].getAttribute("src");
const result = cesiumScriptRegex.exec(src);
if (result !== null) {
return result[1];
}
}
return undefined;
}
let a;
function tryMakeAbsolute(url) {
if (typeof document === "undefined") {
//Node.js and Web Workers. In both cases, the URL will already be absolute.
return url;
}
if (!when.defined(a)) {
a = document.createElement("a");
}
a.href = url;
// IE only absolutizes href on get, not set
// eslint-disable-next-line no-self-assign
a.href = a.href;
return a.href;
}
let baseResource;
function getCesiumBaseUrl() {
if (when.defined(baseResource)) {
return baseResource;
}
let baseUrlString;
if (typeof CESIUM_BASE_URL !== "undefined") {
baseUrlString = CESIUM_BASE_URL;
} else if (
typeof define === "object" &&
when.defined(define.amd) &&
!define.amd.toUrlUndefined &&
when.defined(require.toUrl)
) {
baseUrlString = getAbsoluteUri(
"..",
buildModuleUrl("Core/buildModuleUrl.js")
);
} else {
baseUrlString = getBaseUrlFromCesiumScript();
}
//>>includeStart('debug', pragmas.debug);
if (!when.defined(baseUrlString)) {
throw new RuntimeError.DeveloperError(
"Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL."
);
}
//>>includeEnd('debug');
baseResource = new Resource({
url: tryMakeAbsolute(baseUrlString),
});
baseResource.appendForwardSlash();
return baseResource;
}
function buildModuleUrlFromRequireToUrl(moduleID) {
//moduleID will be non-relative, so require it relative to this module, in Core.
return tryMakeAbsolute(require.toUrl(`../${moduleID}`));
}
function buildModuleUrlFromBaseUrl(moduleID) {
const resource = getCesiumBaseUrl().getDerivedResource({
url: moduleID,
});
return resource.url;
}
let implementation;
/**
* Given a relative URL under the Cesium base URL, returns an absolute URL.
* @function
*
* @param {String} relativeUrl The relative path.
* @returns {String} The absolutely URL representation of the provided path.
*
* @example
* const viewer = new Cesium.Viewer("cesiumContainer", {
* imageryProvider: new Cesium.TileMapServiceImageryProvider({
* url: Cesium.buildModuleUrl("Assets/Textures/NaturalEarthII"),
* }),
* baseLayerPicker: false,
* });
*/
function buildModuleUrl(relativeUrl) {
if (!when.defined(implementation)) {
//select implementation
if (
typeof define === "object" &&
when.defined(define.amd) &&
!define.amd.toUrlUndefined &&
when.defined(require.toUrl)
) {
implementation = buildModuleUrlFromRequireToUrl;
} else {
implementation = buildModuleUrlFromBaseUrl;
}
}
const url = implementation(relativeUrl);
return url;
}
// exposed for testing
buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
buildModuleUrl._buildModuleUrlFromBaseUrl = buildModuleUrlFromBaseUrl;
buildModuleUrl._clearBaseResource = function () {
baseResource = undefined;
};
/**
* Sets the base URL for resolving modules.
* @param {String} value The new base URL.
*/
buildModuleUrl.setBaseUrl = function (value) {
baseResource = Resource.DEFAULT.getDerivedResource({
url: value,
});
};
/**
* Gets the base URL for resolving modules.
*/
buildModuleUrl.getCesiumBaseUrl = getCesiumBaseUrl;
/**
* An IAU 2006 XYS value sampled at a particular time.
*
* @alias Iau2006XysSample
* @constructor
*
* @param {Number} x The X value.
* @param {Number} y The Y value.
* @param {Number} s The S value.
*
* @private
*/
function Iau2006XysSample(x, y, s) {
/**
* The X value.
* @type {Number}
*/
this.x = x;
/**
* The Y value.
* @type {Number}
*/
this.y = y;
/**
* The S value.
* @type {Number}
*/
this.s = s;
}
/**
* A set of IAU2006 XYS data that is used to evaluate the transformation between the International
* Celestial Reference Frame (ICRF) and the International Terrestrial Reference Frame (ITRF).
*
* @alias Iau2006XysData
* @constructor
*
* @param {Object} [options] Object with the following properties:
* @param {Resource|String} [options.xysFileUrlTemplate='Assets/IAU2006_XYS/IAU2006_XYS_{0}.json'] A template URL for obtaining the XYS data. In the template,
* `{0}` will be replaced with the file index.
* @param {Number} [options.interpolationOrder=9] The order of interpolation to perform on the XYS data.
* @param {Number} [options.sampleZeroJulianEphemerisDate=2442396.5] The Julian ephemeris date (JED) of the
* first XYS sample.
* @param {Number} [options.stepSizeDays=1.0] The step size, in days, between successive XYS samples.
* @param {Number} [options.samplesPerXysFile=1000] The number of samples in each XYS file.
* @param {Number} [options.totalSamples=27426] The total number of samples in all XYS files.
*
* @private
*/
function Iau2006XysData(options) {
options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
this._xysFileUrlTemplate = Resource.createIfNeeded(
options.xysFileUrlTemplate
);
this._interpolationOrder = when.defaultValue(options.interpolationOrder, 9);
this._sampleZeroJulianEphemerisDate = when.defaultValue(
options.sampleZeroJulianEphemerisDate,
2442396.5
);
this._sampleZeroDateTT = new JulianDate(
this._sampleZeroJulianEphemerisDate,
0.0,
TimeStandard$1.TAI
);
this._stepSizeDays = when.defaultValue(options.stepSizeDays, 1.0);
this._samplesPerXysFile = when.defaultValue(options.samplesPerXysFile, 1000);
this._totalSamples = when.defaultValue(options.totalSamples, 27426);
this._samples = new Array(this._totalSamples * 3);
this._chunkDownloadsInProgress = [];
const order = this._interpolationOrder;
// Compute denominators and X values for interpolation.
const denom = (this._denominators = new Array(order + 1));
const xTable = (this._xTable = new Array(order + 1));
const stepN = Math.pow(this._stepSizeDays, order);
for (let i = 0; i <= order; ++i) {
denom[i] = stepN;
xTable[i] = i * this._stepSizeDays;
for (let j = 0; j <= order; ++j) {
if (j !== i) {
denom[i] *= i - j;
}
}
denom[i] = 1.0 / denom[i];
}
// Allocate scratch arrays for interpolation.
this._work = new Array(order + 1);
this._coef = new Array(order + 1);
}
const julianDateScratch = new JulianDate(0, 0.0, TimeStandard$1.TAI);
function getDaysSinceEpoch(xys, dayTT, secondTT) {
const dateTT = julianDateScratch;
dateTT.dayNumber = dayTT;
dateTT.secondsOfDay = secondTT;
return JulianDate.daysDifference(dateTT, xys._sampleZeroDateTT);
}
/**
* Preloads XYS data for a specified date range.
*
* @param {Number} startDayTT The Julian day number of the beginning of the interval to preload, expressed in
* the Terrestrial Time (TT) time standard.
* @param {Number} startSecondTT The seconds past noon of the beginning of the interval to preload, expressed in
* the Terrestrial Time (TT) time standard.
* @param {Number} stopDayTT The Julian day number of the end of the interval to preload, expressed in
* the Terrestrial Time (TT) time standard.
* @param {Number} stopSecondTT The seconds past noon of the end of the interval to preload, expressed in
* the Terrestrial Time (TT) time standard.
* @returns {Promisex
axis points in the local east direction.y
axis points in the local north direction.z
axis points in the direction of the ellipsoid surface normal which passes through the position.x
axis points in the local north direction.y
axis points in the local east direction.z
axis points in the opposite direction of the ellipsoid surface normal which passes through the position.x
axis points in the local north direction.y
axis points in the direction of the ellipsoid surface normal which passes through the position.z
axis points in the local east direction.x
axis points in the local north direction.y
axis points in the local west direction.z
axis points in the direction of the ellipsoid surface normal which passes through the position.